1、代码php
<?php /** * 面向对象的形式 + task + timer */ class WebsocketTest { public $server; public function __construct() { $this->server = new Swoole\WebSocket\Server("0.0.0.0", 9502); $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']); $this->server->start(); } public function onOpen(swoole_websocket_server $server, $request) { echo "server: handshake success with fd{$request->fd}".PHP_EOL; } /** * 监听我是消息事件 * * @param Swoole\WebSocket\Server $server * @param [type] $frame * @return void */ public function onMessage(Swoole\WebSocket\Server $server, $frame) { echo "receive from {$frame->fd}:{$frame->data}, opcode:{$frame->opcode}, fin:{$frame->finish}".PHP_EOL; $data = [ 'task' => 1, 'fd' => $frame->fd, ]; // 投放一个 异步 onTask任务 todo 10s $server->task($data); // 开始一个定时任务 每隔多少时间执行 if ($frame->fd == 1) { swoole_timer_tick(2000, function ($timer_id) { echo '2s: timerId:'.$timer_id.PHP_EOL; }); } // 指定的时间后执行 比下面的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, "this is server ".date('Y-m-d H:i:s')); } /** * @param swoole_server $serv * @param [type] $task_id * @param [type] $src_worker_id * @param [type] $data * @return void */ public function onTask(swoole_server $serv, $task_id, $src_worker_id, $data) { // print_r($data); echo 'task start:'.date("Y-m-d H:i:s").PHP_EOL; // 模拟耗时场景 sleep(10); // onFinsh 告诉worker return "after 10 seconds, on task finish\n"; } public function onFinish($serv, $task_id, $data) { echo 'taskId:'.$task_id.' && '; // onTask 返回的内容 echo 'task finished && data is '.$data; } public function onClose($ser, $fd) { echo "client {$fd} closed\n"; } } new WebsocketTest();
客户端用的仍是原来的 ws_client.htmlhtml