https://wiki.swoole.com/wiki/page/41.html
<?php class wsServer { const Host = '0.0.0.0'; const PORT = '9504'; public $ws = null; function __construct() { $this->ws = new swoole_websocket_server(self::Host, self::PORT); $this->ws->set([ 'worker_num' => 2, //worker 进程数 电好CPU 1-4 'task_worker_num' => 2 ]); $this->ws->on('open', [$this, 'onOpen']); $this->ws->on('message', [$this, 'onMessage']); $this->ws->on('task', [$this, 'onTask']); $this->ws->on('finish', [$this, 'onFinish']); $this->ws->on('close', [$this, 'onClose']); $this->ws->start(); } /**S * 监听websocke连接打开事件 * @param $server * @param $request */ function onOpen($server, $request) { print_r($request->fd); } /** * 监听消息事件 * 向websocket客户端连接推送数据 * $fd 客户端连接的ID,如果指定的$fd对应的TCP连接并非websocket客户端,将会发送失败 * $data 要发送的数据内容 * $opcode,指定发送数据内容的格式,默认为文本。发送二进制内容$opcode参数需要设置为WEBSOCKET_OPCODE_BINARY * 发送成功返回true,发送失败返回false * function swoole_websocket_server->push(int $fd, string $data, int $opcode = 1, bool $finish = true); * @param $ws * @param $frame */ function onMessage($ws, $frame) { // echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n"; //task 代码只是提交,不影响下面的PUSH $data = [ 'task' => 1, //编号 'fd' => $frame->fd //客户端ID ]; $ws->task($data); $ws->push($frame->fd, "this is server"); } /** * @param $serv * @param $taskId * @param $workerId * @param $data * @return string */ public function onTask($serv, $taskId, $workerId, $data) { print_r($data); //处理的逻辑,耗时场景 sleep(10); return 'on task finish'; // 告诉worker } public function onFinish($serv, $taskId, $data) { echo 'taskId'. $taskId; //data内容是onTask return内容 echo ' finish-data-succ'.$data; } /** * 关闭 * @param $ws * @param $fd */ function onClose($ws, $fd) { echo "client {$fd} closed\n"; } } $ws = new wsServer();