美文网首页
Swoole入门 - WebSocket 服务[面向对象]

Swoole入门 - WebSocket 服务[面向对象]

作者: 铁匠简记 | 来源:发表于2019-06-02 00:38 被阅读0次

我们之前的server都是面向过程的,本篇示例用面向对象的思想去重构WebSocketServer。

class WS {
    public $server;
    public function __construct() {
        $this->server = new Swoole\WebSocket\Server("0.0.0.0", 8812);
        $this->server->on('open', [$this, 'onOpen']);
        $this->server->on('message', [$this, 'onMessage']);
        $this->server->on('close', [$this, 'onClose']);

        $this->server->start();
    }

    /**
     * 监听websocket的打开连接事件
     * @param $server
     * @param $request
     */
    public function onOpen($server,$request)
    {
        echo "server: handshake success with fd{$request->fd}\n";
    }

    /**
     * 监听websocket的消息事件
     * @param $server
     * @param $frame
     */
    public function onMessage($server,$frame)
    {
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
        $server->push($frame->fd, "this is server");
    }

    /**
     * 监听websocket的关闭连接事件
     * @param $server
     * @param $fd
     */
    public function onClose($server,$fd)
    {
        echo "client {$fd} closed\n";
    }
}
$obj = new WS();
new WebsocketTest();

再去使用上篇的方法测试,依然有效。

相关文章

网友评论

      本文标题:Swoole入门 - WebSocket 服务[面向对象]

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