hyperf框架WebSocket 服务

1:安装

composer require hyperf/websocket-server

2:配置 Server   修改 config/autoload/server.php,增加以下配置。


return [
    'servers' => [
        [
            'name' => 'ws',
            'type' => Server::SERVER_WEBSOCKET,
            'host' => '0.0.0.0',
            'port' => 9502,
            'sock_type' => SWOOLE_SOCK_TCP,
            'callbacks' => [
                Event::ON_HAND_SHAKE => [Hyperf\WebSocketServer\Server::class, 'onHandShake'],
                Event::ON_MESSAGE => [Hyperf\WebSocketServer\Server::class, 'onMessage'],
                Event::ON_CLOSE => [Hyperf\WebSocketServer\Server::class, 'onClose'],
            ],
        ],
    ],
];

3:配置路由 在 config/routes.php 文件内增加对应 ws 的 Server 的路由配置,这里的 ws 值取决于您在 config/autoload/server.php 内配置的 WebSocket Server 的 name 值。

Router::addServer('ws', function () {
    Router::get('/', 'App\Controller\WebSocketController');
});

4:创建控制器

data 前端发过来的数据
        $data = [
            "小敏!",
            "小明",
            "小米",
            "华维",
            "苹果"
        ];
        $rand = rand(0,4);
        $server->push($frame->fd, '后端: ' . $data[$rand]);
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        echo $fd . '断开连接,处理线程是 ' . $reactorId . PHP_EOL;
    }

    public function onOpen($server, $request): void
    {
        $server->push($request->fd, $request->fd . ' 号客户端已连接!' . PHP_EOL);
    }
}

5:前端页面测试




    
    
    
    websocket


    你可能感兴趣的:(php,hyperf,html,websocket,网络协议,网络)