💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
Swoole作为Server时,[回调函数](https://wiki.swoole.com/wiki/page/41.html)有很多。但可以简单分个类: 1) 进程启动时执行的:onStart、onManagerStart、onWorkerStart;onWorkerStop、onManagerStop、onShutdown;onWorkerError 2) 客户端交互时触发的:onReceive/onRequest/onPacket/onMessage、onOpen/onConnect、onClose 3) Task:onTask、onFinish 4) Timer:onTimer 事件执行顺序: - 所有事件回调均在`$server->start`后发生 - 服务器关闭程序终止时最后一次事件是`onShutdown` - 服务器启动成功后,`onStart/onManagerStart/onWorkerStart`会在不同的进程内并发执行。 - `onReceive/onConnect/onClose/onTimer`在worker进程(包括task进程)中各自触发 - worker/task进程启动/结束时会分别调`用onWorkerStart/onWorkerStop` - `onTask`事件仅在task进程中发生 - onFinish事件仅在worker进程中发生 - `onStart/onManagerStart/onWorkerStart` 3个事件的执行顺序是不确定的 - UDP协议下只有`onReceive`事件,没有`onConnect/onClose`事件 - 如果未设置`onPacket`回调函数,收到UDP数据包默认会回调`onReceive`函数 - `onOpen`事件回调是可选的:当WebSocket客户端与服务器建立连接并完成握手后会回调此函数 实际使用的时候不是所有回调都可以使用的,例如UDP服务器没有`onConnect/onClose`;例如接收数据,在WebSocket里使用onReceive,在HttpServer使用onRequest,在UDPServer使用onPacket。 示例: ``` php <?php $server = new \swoole_server("127.0.0.1",8088); $server->set(array( 'daemonize' => false, 'reactor_num' => 2, 'worker_num' => 4 )); $server->on('connect', function ($serv, $fd){ echo "client connect. fd is {$fd}\n"; }); $server->on('receive', function ($serv, $fd, $from_id, $data){ echo "client connect. fd is {$fd}\n"; }); $server->on('close', function ($serv, $fd){ echo "client close. fd is {$fd}\n"; }); // 以下回调发生在Master进程 $server->on("start", function (\swoole_server $server){ echo "On master start.\n"; }); $server->on('shutdown', function (\swoole_server $server){ echo "On master shutdown.\n"; }); // 以下回调发生在Manager进程 $server->on('ManagerStart', function (\swoole_server $server){ echo "On manager start.\n"; }); $server->on('ManagerStop', function (\swoole_server $server){ echo "On manager stop.\n"; }); // 以下回调也发生在Worker进程 $server->on('WorkerStart', function (\swoole_server $server, $worker_id){ echo "Worker start\n"; }); $server->on('WorkerStop', function(\swoole_server $server, $worker_id){ echo "Worker stop\n"; }); $server->on('WorkerError', function(\swoole_server $server, $worker_id, $worker_pid, $exit_code){ echo "Worker error\n"; }); $server -> start(); ```