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:创建控制器
- declare(strict_types=1);
-
- namespace App\Controller;
-
- use Hyperf\Contract\OnCloseInterface;
- use Hyperf\Contract\OnMessageInterface;
- use Hyperf\Contract\OnOpenInterface;
- use Hyperf\WebSocketServer\Constant\Opcode;
- use Swoole\Server;
- use Swoole\WebSocket\Server as WebSocketServer;
-
- class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
- {
- public function onMessage($server, $frame): void
- {
- // $frame->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:前端页面测试
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport"
- content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>websockettitle>
- head>
- <body>
- <div>
- <textarea name="content" id="content" cols="30" rows="10">textarea>
- <button onclick="send();">发送button>
- div>
- <ul id="messageList">ul>
-
- <script>
- let ws = new WebSocket('ws://127.0.0.1:9101')
- ws.onopen = event => {
- console.log('连接服务器成功');
- }
-
- ws.onmessage = event => {
- let data = event.data;
- let ul = document.getElementById('messageList');
- let li = document.createElement('li');
- li.innerHTML = data;
- ul.appendChild(li);
- }
-
- ws.onclose = event => {
- console.log('客户端连接关闭');
- }
-
- function send() {
- let obj = document.getElementById('content');
- let content = obj.value;
-
- let ul = document.getElementById('messageList');
- let li = document.createElement('li');
- li.innerHTML = "我:"+content;
- ul.appendChild(li);
-
- ws.send(content);
- obj.value = '';
- }
- script>
- body>
- html>