您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

swoole怎么异步调用

2024/3/11 21:56:18发布26次查看
swoole怎么异步调用?
swoole中的异步使用
测试案例:
改写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接受数据并输出。
用户页面:
<!doctype html><head><meta charset="utf-8"><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title></title></head><body><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");//输出在页面} //实例化 onmessagewebsocket.onmessage = function(evt) { console.log("ws-server-return-data:"+evt.data);} //实例化onclosewebsocket.onclose = function(evt) { console.log("close");} //实例化onerrorwebsocket.onerror =function(evt,e) { console.log("error:"+evt.data);}</script></body></html>
浏览器:(客户端)
服务器:
第一行数据为服务端输出,一开始建立连接的onopen(),之后先由客户端(ws_client.html)通过js代码连接并发送数据;第二行为发送数据前打印;发送数据到服务端后,执行onmessage();其中再次输出数据并建立task,调用ontask();在其中再次输出数据并返回数据给onfinish();
服务器端直接输出是到服务器,客户端需要通过push,send等发送到服务器
客户端通过console.log打印数据到页面
异步体现
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"));}
这段代码中建立一个task任务之后,不会等到任务执行完之后再push,而是会同时进行。在客户端打印并发送数据后,客户端打印的数据与onmessage中的输出间隔很短,并不会受ontask任务中sleep的影响。
以上就是swoole怎么异步调用的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product