onRequest回调

abbychau 1月前 24

onRequest回调

swoole_websocket_server 继承自 swoole_http_server

  • 设置了onRequest回调,websocket服务器也可以同时作为http服务器
  • 未设置onRequest回调,websocket服务器收到http请求后会返回http 400错误页面
  • 如果想通过接收http触发所有websocket的推送,需要注意作用域的问题,面向过程请使用“global”对swoole_websocket_server进行引用,面向对象可以把swoole_websocket_server设置成一个成员属性

1、面向过程代码

$server = new swoole_websocket_server("0.0.0.0", 9501);$server->on('open', function (swoole_websocket_server $server, $request) {        echo "server: handshake success with fd{$request->fd}\n";
    });$server->on('message', function (swoole_websocket_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->on('request', function (swoole_http_request $request, swoole_http_response $response) {        global $server;//调用外部的server
        // $server->connections 遍历所有websocket连接用户的fd,给所有用户推送
        foreach ($server->connections as $fd) {            $this->server->push($fd, $request->get['message']);
        }
    });$server->start();


最新回復 (0)
返回
發新帖
作者最近主题: