作者:吻过彩虹的脸_378 | 2022-11-26 16:48
swoole异步调用的方法:首先改写“ws_server.php”文件;然后建立连接的“onOpen()”;接着由客户端“ws_client.html”通过js代码连接并发送数据;最后客户端通过“console.log”打印数据到页面即可。
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接受数据并输出。
用户页面:
chuangxiang--测试