美文网首页PHP干货分享
yii+swoole上手websocket(1)—— demo

yii+swoole上手websocket(1)—— demo

作者: JUNE言JUNE语 | 来源:发表于2019-12-11 23:59 被阅读0次

    给自己找一点事情做~

    说明:利用yii框架纯粹只是避免重复造轮子~~
    先撸一个hello world吧

    [Talk is cheap. Show me the code]

    这一段是从官网copy下来的服务端代码,贼好使

    use \Swoole\WebSocket\Server;
    $server = new Server("0.0.0.0", 9501);
    $server->on('open', function (Server $server, $request) {
        echo "server: handshake success with fd{$request->fd}\n";
    });
    $server->on('message', function (Server $server, $frame) {
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
        $server->push($frame->fd, "this is server");
    });
    $server->on('close', function ($ser, $fd) {
        echo "client {$fd} closed\n";
    });
    $server->start();
    
    服务端执行结果

    再手撸一段客户端代码~

    $cli = new \swoole_http_client('127.0.0.1', 9501);
    $cli->setHeaders(['Trace-Id' => md5(time()),]);
    $cli->on('message', function ($_cli, $frame) {
        var_dump($frame);
        $_cli->close();
    });
    $cli->upgrade('/', function ($cli) {
        echo $cli->body;
        echo 'upgrade'. PHP_EOL;
        $cli->push("hello world");
    });
    
    客户端执行结果

    说明:
    这里暂时不会考虑ssl等加密问题,一般情况下,需要加上ssl,也是通过一层nginx代理

    相关文章

      网友评论

        本文标题:yii+swoole上手websocket(1)—— demo

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