1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| <?php use Swoole\Process;
/** * 创建Server 对象,监听本地 9501 端口。 */ $server = new Swoole\Server("0.0.0.0", 9501);
$workers = [];
/** * 监听连接进入事件 */ $server->on("Connect", function ($server, $fd) { global $workers; // 创建子进程 $process = new swoole_process(function (swoole_process $worker) use ($server, $fd) { echo "Client Connect" . PHP_EOL;
// todo 业务逻辑 ... // 向客户端推送消息 $server->send($fd, $str); }, true, 0, false); // 启动子进程 $pid = $process->start(); array_push($workers, ["pid" => $pid, "fd" => $fd]); });
/** * 监听数据接收事件 */ $server->on("Receive", function ($server, $fd, $from_id, $data){ $server->send($fd, "Server: " . $data); });
/** * 监听连接关闭事件 */ $server->on("Close", function ($server, $fd) { global $workers; foreach ($workers as $worker) { if ($worker['fd'] === $fd){ // 检查子进程是否存在 if (Process::kill($worker['pid'], 0)){ array_shift($worker); // 通过信号终止子进程 Process::kill($worker['pid'], SIGKILL); } } } echo "Client Close" . PHP_EOL; });
// 启动TCP 服务器 $server->start();
|