<?php
/**
* ws优化 + task机制 + 毫秒定时器
*/
class Ws
{
CONST HOST = "0.0.0.0";
CONST PORT = 8812;
public $ws = null;
public function __construct()
{
$this->ws = new swoole_websocket_server("0.0.0.0", 8812);
$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']);
$this->ws->start();
}
/**
* 监听ws连接事件
* @Author Jartin
* @Url string
* @DateTime 2020-03-22T19:23:40+0800
* @param [type] $ws [description]
* @param [type] $request [description]
* @return [type] [description]
*/
public function onOpen($ws, $request)
{
var_dump($request->fd);
// 定时器 将客户端标识为1的每两秒执行一次
if ($request->fd == 1) {
swoole_timer_tick(2000, function($timer_id) {
echo "两秒执行的结果 定时器id为:{$timer_id}\n";
});
}
}
/**
* 监听ws消息事件
* @Author Jartin
* @Url string
* @DateTime 2020-03-22T19:25:25+0800
* @param [type] $ws [description]
* @param [type] $frame [description]
* @return [type] [description]
*/
public function onMessage($ws, $frame)
{
echo "服务端监听到客户端的消息:{$frame->data}\n";
// 此处假设10s执行代码 使用task 做个投递任务
$data = [
'task' => 1,
'fd' => $frame->fd,
];
// $ws->task($data); // 执行到此处task不会阻塞 会直接执行push
swoole_timer_after(5000, function() use($ws, $frame) {
echo "服务端监听到客户端的消息5秒之后 想客户端发送的定时器信息\n";
$ws->push($frame->fd, '5秒之后执行定时器');
}); // 异步定时器 执行到此处task不会阻塞 会直接执行push(↓↓↓↓)
$ws->push($frame->fd, "服务端返回给客户端数据:" . date('Y-m-d H:i:s', time()));
}
public function onTask($serv, $tash_id, $worker_id, $data)
{
print_r($data);
// 假设场景耗时10s
sleep(10);
return "on task finish";// 告诉worker
}
// 此处的$data为 ’on task finish‘
public function onFinish($serv, $taskId, $data)
{
echo "taskId:{$taskId}\n";
echo "task结果接收成功:{$data}";
}
/**
*
* @Author Jartin
* @Url string
* @DateTime 2020-03-22T19:28:44+0800
* @param [type] $ws [description]
* @param [type] $fd [description]
* @return [type] [description]
*/
public function onClose($ws, $fd)
{
echo "客户端ID:{$fd}\n";
}
}
$obj = new Ws();