一、代码
<?php use SwooleServer; /** * 面向对象的形式 + task + timer */ class WebSocket { public $server; public function __construct() { $this->server = new SwooleWebSocketServer("0.0.0.0", 9501); $this->server->set([ 'worker_num' => 2, 'task_worker_num' => 2 ]); // 注册事件回调 $this->server->on('open', [$this, 'onOpen']); $this->server->on('message', [$this, 'onMessage']); $this->server->on('task', [$this, 'onTask']); $this->server->on('finish', [$this, 'onFinish']); $this->server->on('close', [$this, 'onClose']); } public function run() { $this->server->start(); } public function onOpen(Server $server, $request) { echo "server: handshake success with fd{$request->fd}" . PHP_EOL; } /** * 监听我是消息事件 * @param SwooleWebSocketServer $server * @param SwooleWebsocketFrame $frame 包含了客户端发来的数据帧信息 */ public function onMessage(SwooleWebSocketServer $server, SwooleWebsocketFrame $frame) { echo "receive from {$frame->fd}:{$frame->data}, opcode:{$frame->opcode}, fin:{$frame->finish}" . PHP_EOL; $data = [ 'task' => 1, 'fd' => $frame->fd, ]; // 投放一个 异步 onTask任务 $server->task($data); if ($frame->fd == 1) { $times = 3; // 开始一个定时任务 每隔2s执行 swoole_timer_tick(2000, function ($timerId) use ($server, $frame, &$times) { if ($times > 0) { echo '1s: timerId:' . $timerId . PHP_EOL; $times--; } else { swoole_timer_clear($timerId); $server->push($frame->fd, 'timer tick over'); } }); } // 指定的时间后执行 比下面的push后执行(异步)10s swoole_timer_after(10000, function () use ($server, $frame) { $server->push($frame->fd, "task finished " . date('Y-m-d H:i:s')); }); // 不会堵塞 返回给客户端信息 $server->push($frame->fd, "服务器返回数据"); } /** * 处理一些耗时的任务 * @param Server $serv * @param int $taskId 任务ID * @param int $srcWorkerId 来自于哪个worker进程 * @param mixed $data 异步投递的数据 任务的内容 * @return string */ public function onTask(Server $serv, $taskId, $srcWorkerId, $data) { // 处理一些耗时的任务 // print_r($data); sleep(10); if (isset($data['fd'])) { $serv->push($data['fd'], 'task start:' . date("Y-m-d H:i:s")); } // onFinsh 告诉worker进程 return "我是任务处理完后回调" . PHP_EOL; } /** * 任务处理完后执行 * @param Server $serv * @param int $taskId * @param string $data onTask返回的内容 */ public function onFinish(Server $serv, $taskId, $data) { echo 'taskId:' . $taskId . ' && task finished && data is ' . $data; } /** * TCP客户端连接关闭 * @param Server $ser * @param int $fd * @param int $reactorId 来自那个reactor线程 */ public function onClose(Server $ser, $fd, $reactorId) { echo "client {$fd} closed "; } } $server = new WebSocket(); $server->run();
客户端用的还是原来的 ws_client.html
服务器输出: