swoole 简单聊天室

最开始想laravel+swoole打造一个简单的聊天室
然后开启server时候发现没必要,在哪写都一样
所以我另外在laravel外面写了个server的目录,用作简单调试


image.png

以下是代码块
swooleServer.php

server = new \Swoole\WebSocket\Server("0.0.0.0", 9501);
    }

    public function go()
    {

        // 客户端链接时候触发
        $this->server->on('open', function (Swoole\WebSocket\Server $server, $request) {
            echo "server: handshake success with fd{$request->fd}\n";
        });
        // 客户端发送消息的时候触发
        $this->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, "{$frame->data}");
            // 获取到里面所有的链接id,然后逐个广播
            foreach ($this->server->connections as $fd) {
                // 需要先判断是否是正确的websocket连接,否则有可能会push失败
                if ($this->server->isEstablished($fd)) {
                    // push到server 然后客户端接收
                    $this->server->push($fd, json_encode(['on'=>$frame->fd,'msg'=>$frame->data]));
                }
            }
        });
        // 客户端关闭链接的时候触发
        $this->server->on('close', function ($ser, $fd) {
            echo "client {$fd} closed\n";
        });

        // 运行server
        $this->server->start();
    }
}

$ser = new swooleServer();
$ser->go();

用户1的view。user/profile.blade.php




    
    
    
    Document


用户1:
展示内容

用户2的view,home/profile.blade.php




    
    
    
    Document


用户2:
展示内容

最终效果


image.png

你可能感兴趣的:(swoole 简单聊天室)