美文网首页
swoole之websocket之协程版和回调版

swoole之websocket之协程版和回调版

作者: 江江简书 | 来源:发表于2021-01-04 08:52 被阅读0次

    项目要用到消息提醒功能,因此借此机会学习websocket

    回调版本websocket

    <?php
    //创建WebSocket Server对象,监听0.0.0.0:9502端口
    $ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);
    
    //监听WebSocket连接打开事件
    $ws->on('open', function ($ws, $request) {
        var_dump('客户连进来了');
        $ws->push($request->fd, "hello, welcome\n");
    });
    
    //监听WebSocket消息事件
    $ws->on('message', function ($ws, $frame) {
        echo "Message: {$frame->data}\n";
        $ws->push($frame->fd, "server: {$frame->data}");
        $ws->push($frame->fd, "i am coming");
    });
    
    //利用swoole的定时器,定时请求第三方接口,将数据实时推送到客户端即可;timer的简单用法
    $ws->on('WorkerStart', function ($ws, $worker_id){
        Swoole\Timer::tick(5000, function (int $timer_id, $ws) {
            echo "timer_id #$timer_id, after 5000ms.\n";
            foreach ($ws->connections  as $fd){
                var_dump($fd);
                $rand = mt_rand(0,1000);
                $ws->push($fd, $rand);
            }
        }, $ws);
    });
    
    //监听WebSocket连接关闭事件
    $ws->on('close', function ($ws, $fd) {
        echo "client-{$fd} is closed\n";
    });
    
    $ws->start();
    //主要是实现了隔5秒主动发消息到连接的客户
    

    协程版本websocket

    Co\run(function () {
        $server = new Co\Http\Server('0.0.0.0', 9502, false);
        $server->handle('/websocket', function ($request, $ws) {
            $ws->upgrade();
            while (true) {
                $frame = $ws->recv();
                if ($frame === '') {
                    $ws->close();
                    break;
                } else if ($frame === false) {
                    echo "error : " . swoole_last_error() . "\n";
                    break;
                } else {
                    if ($frame->data == 'close' || get_class($frame) === Swoole\WebSocket\CloseFrame::class) {
                        $ws->close();
                        return;
                    }
                    $ws->push("Hello {$frame->data}!");
                    $ws->push("How are you, {$frame->data}?");
                }
                var_dump($ws->fd);
                Swoole\Timer::tick(5000, function (int $timer_id, $ws) {
                        echo "timer_id #$timer_id, after 5000ms.\n";
                        $rand = mt_rand(0,1000);
                        $ws->push($rand);
                    }, $ws);
            }
        });
        $server->start();
    });
    

    相关文章

      网友评论

          本文标题:swoole之websocket之协程版和回调版

          本文链接:https://www.haomeiwen.com/subject/ueumoktx.html