Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Swoole Server instance


May 14, 2021 Swoole


Table of contents


Introduction to Swoole Server

Create an asynchronous server program that supports TCP, UDP, UnixSocket 3 protocols, IPv4 and IPv6, and tunnel encryption for SSL/TLS one-way two-way certificates. Consumers don't need to pay attention to the underlying implementation details, they just need to set up callback functions for network events.

swoole_server can only be used in php-cli environments, otherwise fatal errors can be thrown

Build a server object

$serv = new swoole_server("127.0.0.1", 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP);

Set runtime parameters

$serv->set(array(
    'worker_num' => 4,
    'daemonize' => true,
    'backlog' => 128,
));

Register the event callback function

$serv->on('Connect', 'my_onConnect');
$serv->on('Receive', 'my_onReceive');
$serv->on('Close', 'my_onClose');

There are four styles of callback functions that can be used in PHP

Start the server

$serv->start();

The list of properties

$serv->manager_pid;  //管理进程的PID,通过向管理进程发送SIGUSR1信号可实现柔性重启
$serv->master_pid;  //主进程的PID,通过向主进程发送SIGTERM信号可安全关闭服务器
$serv->connections; //当前服务器的客户端连接,可使用foreach遍历所有连接

Run the flowchart

Swoole Server instance

Process/thread structure diagram

Swoole Server instance

Simple Swoole tcp server instance:

$serv = new Swoole\Server("127.0.0.1", 9501);

//设置服务器参数
$serv->set(array(
    'worker_num' => 8,   //工作进程数量
    'daemonize' => true, //是否作为守护进程
));

//设置事件回调函数
$serv->on('connect', function ($serv, $fd) {
    echo "Client:Connect.\n";
});

$serv->on('receive', function ($serv, $fd, $reactor_id, $data) {
    $serv->send($fd, 'Swoole: ' . $data);
    $serv->close($fd);
});

$serv->on('close', function ($serv, $fd) {
    echo "Client: Close.\n";
});

//启动服务器
$serv->start();