swoole学习之毫秒定时器timer使用案例
websocket服务中加入定时器
<?php
/*swoole定时器
*
* */
class WsTimer
{
//定义host
const HOST = '0.0.0.0';
//定义端口号
const PORT = 9502;
//定义变量
public $ws = '';
//构造函数
public function __construct()
{
$this->ws = new Swoole\WebSocket\Server(self::HOST, self::PORT);
//设置参数
$this->ws->set([
'worker_num' => 2,//设置进程数
]);
//定义方法
$this->ws->on('open', [$this, 'onOpen']);
$this->ws->on('message', [$this, 'onMessage']);
$this->ws->on('close', [$this, 'onClose']);
//启动服务
$this->ws->start();
}
//定义链接websocket服务事件的方法
public function onOpen($ws, $request)
{
/* echo "得到客户端的request请求<pre>";
print_r($request);
*/
//异步毫秒定时器,每隔一段时间,就执行
//当客户端id==1时就执行
if ($request->fd == 1) {
//每2秒,执行一次
swoole_timer_tick(2000, function ($timer_id) {
echo '间隔2s-$timer_id-' . $timer_id . '-' . date('Y-m-d H:i:s', time()) . PHP_EOL;
});
}
}
//定义websocket服务消息事件的方法
public function onMessage($ws, $frame)
{
echo '获取到客户端发送过来的数据' . $frame->data;
//接收到客户端消息5s之后执行命令
swoole_timer_after(5000, function () use ($ws, $frame) {
echo '5s-after-start' . date('Y-m-d H:i:s', time()) . PHP_EOL;
$ws->push($frame->fd, 'wesocketServe-push-data:www.QIPA250.com' . date('Y-m-d H:i:s', time()) . PHP_EOL);
});
//给客户端回应,发送内容
$ws->push($frame->fd, 'wesocketServe-push-data:www.qipa250.com' . date('Y-m-d H:i:s', time()) . PHP_EOL);
}
//定义关闭websocket服务的方法
public function onClose($ws, $fd)
{
echo '客户端:' . $fd . '断开了websocket服务!';
}
}
//实例化
$ws = new WsTimer();
?>
浏览器中查看效果
http://20.20.24.131:9501/websocket.html
红框中可以看到间隔5s之后,服务端又发送了一次数据给客户端,
而服务端,可以看到每2s执行一次指定的内容