测试案例:
改写ws_server.php
$this->ws->set( [ 'worker_num' => 2, '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']); public function onOpen($ws, $request) { var_dump($request->fd); } public function onMessage($ws, $frame) { echo "ser-push-message:{$frame->data}n"; $data = [ 'task' => 1, 'fd' => $frame->fd, ]; $ws->task($data); $ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s")); } public function onTask($serv, $taskId, $workerId, $data) { print_r($data); // 耗时场景 10s sleep(10); return "on task finish"; // 告诉worker } public function onFinish($serv, $taskId, $data) { echo "taskId:{$taskId}n"; echo "finish-data-sucess:{$data}n"; }
客户端,即ws_client.html,发送信息,服务端的onMessage接受并执行设置数据调用onTask,在onTask中打印数据3秒后返回数据给onFinish,onFinish接受数据并输出。
用户页面:
nbsp;html> <meta><meta><title></title><h1>chuangxiang--测试</h1> <script> var wsUrl = "ws://192.168.0.103:8812"; var websocket = new WebSocket(wsUrl); //实例对象的onopen属性 websocket.onopen = function(evt) { websocket.send("Hello chaungxiang");//输出到服务器端,即发送信息 console.log("connected-swoole-success");//输出在页面 } //实例化 onmessage websocket.onmessage = function(evt) { console.log("ws-server-return-data:"+evt.data); } //实例化onclose websocket.onclose = function(evt) { console.log("close"); } //实例化onerror websocket.onerror =function(evt,e) { console.log("error:"+evt.data); } </script>
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
喜欢就支持一下吧
相关推荐