天天看点

swoole 毫秒定时器

<?php
class Ws{
    const HOST = '0.0.0.0';	// 监听的IP地址, 0.0.0.0 表示监听所有IP地址
    const PROT = '9504';

    public $ws = null;	// 存放websocket连接资源
    public $config = [
		// 进程数
        'worker_num' => 2,
	];
	
    public function __construct()
    {
    	// 创建 websocket server对象
        $this->ws = new swoole\websocket\server(self::HOST, self::PROT);
		// 设置参数
        $this->ws->set($this->config);
		// 监听websocket连接事件
        $this->ws->on('open', [$this, 'onOpen']);
        // 监听websocket消息事件
        $this->ws->on('message', [$this, 'onMessage']);
        // 监听websocket连接关闭事件
        $this->ws->on('close', [$this, 'onClose']);
		// 启动服务
        $this->ws->start();
    }

    /**
     * 监听websocket连接事件
     * @param $ws
     * @param $request
     */
    public function onOpen($ws, $request)
    {
        var_dump($request->fd);
    }

    /**
     * 监听websocket消息事件
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame)
    {
        /**
         * 设置一个间隔时间定时器 每2秒执行
         * 回调函数参数 $timer_id 定时器的 ID 清除时使用
         * 回调函数参数 $params.... ,对应 tick 的第三个及之后传入的参数
         */
        $timer = swoole_timer_tick(2000, function($timer_id, $param1, $param2) {
            echo '2s,定时器id: '. $timer_id. PHP_EOL;
            echo $param1. ' - '. $param2. PHP_EOL;  // 第一个参数, 第二个参数
        }, '第一个参数', '第二个参数');

        // 在指定的时间后执行函数 一次性定时器,执行完成后就会销毁
        swoole_timer_after(5000, function() use($ws, $frame, $timer) {
            echo '5s after 关闭定时器'. PHP_EOL;
            // 5s后向客户端发送一条消息
            $ws->push($frame->fd, '我是5s的一次性事件');
            // 清除定时器 参数为定时器id
            swoole_timer_clear($timer);
            // 清除当前 Worker 进程内的所有定时器    需要 Swoole 版本 >= v4.4.0
            swoole_timer_clearAll();
        });
    }
    
    /**
     * 监听websocket连接关闭事件
     * @param $ws
     * @param $fd
     */
    public function onClose($ws, $fd)
    {
        echo '退出了:'. $fd. PHP_EOL;
    }
}
new Ws();