Home > Article > PHP Framework > Think-Swoole's WebSocket-Room joins, leaves the room and sends room messages
Think-Swoole 3.0 added the Room chat room function to Websocket, which is mainly used for group messaging, but messages between different Rooms are isolated from each other. When we enter a chat room, only the fd of this chat room can receive the messages we enter, leave, and send.
config.swoole.php
'websocket' => [ 'enable' => true, 'handler' => Handler::class, 'parser' => Parser::class, 'ping_interval' => 25000, 'ping_timeout' => 60000, 'room' => [ 'type' => 'table', 'table' => [ 'room_rows' => 4096, 'room_size' => 2048, 'client_rows' => 8192, 'client_size' => 2048, ], 'redis' => [ 'host' => '127.0.0.1', 'port' => 6379, 'max_active' => 3, 'max_wait_time' => 5, ], ], 'listen' => [], 'subscribe' => [], ],
There is room configuration item, and the type inside indicates which data processing method is used. There are two types below, "table" and "redis", table is It can be used directly, but redis requires the redis extension to be installed in our system and project. table is a high-performance, cross-process memory processing service that can share data between different processes.
Create events
Enter the following commands in the project root directory to create join room events, leave room events and room chat events respectively:
php think make:listener WsJoin php think make:listener WsLeave php think make:listener RoomTest
Then define the event in app/event.php:
[ ], 'listen' => [ 'AppInit' => [], 'HttpRun' => [], 'HttpEnd' => [], 'LogLevel' => [], 'LogWrite' => [], //监听连接,swoole 事件必须以 swoole 开头 'swoole.websocket.Connect' => [ app\listener\WsConnect::class ], //监听关闭 'swoole.websocket.Close' => [ \app\listener\WsClose::class ], //监听 Test 场景 'swoole.websocket.Test' => [ \app\listener\WsTest::class ], //加入房间事件 'swoole.websocket.Join' => [ \app\listener\WsJoin::class ], //离开房间事件 'swoole.websocket.Leave' => [ \app\listener\WsLeave::class ], //处理聊天室消息 'swoole.websocket.RoomTest' => [ \app\listener\RoomTest::class ], ], 'subscribe' => [ ], ];
The above names such as Join, Leave and RoomTest are all customized and should correspond to the scene value of the message sent by the front end.
Of course, the event definition can also be configured in the websocket listen of the config/swoole.php configuration file. Please refer to the previous article for details.
H5 WebSocker client connection
wsroot.html
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <button onclick="join()">加入房间</button> <button onclick="leave()">离开房间</button> <input type="text" id="message"> <button onclick="send()">发送</button> <script> var ws = new WebSocket("ws://127.0.0.1:9501/?uid=1"); ws.onopen = function(){ console.log('连接成功'); } //数据返回的解析 function mycallback(data){ var start = data.indexOf('[') // 第一次出现的位置 var start1 = data.indexOf('{') if(start < 0){ start = start1; } if(start >= 0 && start1 >= 0){ start = Math.min(start,start1); } if(start >= 0){ console.log(data); var json = data.substr(start); //截取 var json = JSON.parse(json); console.log(json); // if(json instanceof Array){ // window[json[0]](json[1]); // } } } function sendfd($message){ console.log($message) } function testcallback($message){ console.log($message) } function joincallback($message){ // console.log($message) console.log(11); } function leavecallback($message){ console.log($message) } ws.onmessage = function(data){ // console.log(data.data); mycallback(data.data); } ws.onclose = function(){ console.log('连接断开'); } function join() { var room = prompt('请输入房间号'); ws.send(JSON.stringify(['join',{ room:room }])); //发送的数据必须是 ['test',数据] 这种格式 } function leave() { var room = prompt('请输入要离开的房间号'); ws.send(JSON.stringify(['leave',{ room:room }])); //发送的数据必须是 ['test',数据] 这种格式 } function send() { var message = document.getElementById('message').value; var room = prompt('请输入接收消息的房间号') ws.send(JSON.stringify(['RoomTest',{ message:message, room:room }])); //发送的数据必须是 ['test',数据] 这种格式 } </script> </body> </html>
SocketIO client connection
ioroomtest.html
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <button onclick="join()">加入房间</button> <button onclick="leave()">离开房间</button> <input type="text" id="message"> <button onclick="send()">发送</button> <script src="./socketio.js"></script> <script> //http 协议 var socket = io("http://127.0.0.1:9501?uid=1", {transports: ['websocket']}); socket.on('connect', function(){ console.log('connect success'); }); socket.on('close',function(){ console.log('connect close') }); //send_fd 为自定义的场景值,和后端对应 socket.on("sendfd", function (data) { console.log(data) }); //testcallback 为自定义的场景值,和后端对应 socket.on("testcallback", function (data) { console.log(data) }); socket.on("joincallback", function (data) { console.log(data) }); socket.on("roomtestcallback", function (data) { console.log(data) }); function join() { var room = prompt('请输入房间号'); socket.emit('join',{ room : room }); } function leave() { var room = prompt('请输入要离开的房间号'); socket.emit('leave',{ room : room }); } function send() { var message = document.getElementById('message').value; var room = prompt('请输入接收消息的房间号') socket.emit('RoomTest',{ message : message, room : room }); } </script> </body> </html>
In the page, the scene values defined in the join(), leave(), and send() functions are join, leave, and RoomTest respectively. We defined them in app/leave.php These scene values correspond to events and therefore trigger the WsJoin.php, WsLeave.php and RoomTest.php events respectively.
Backend event writing
app/listener/WsJoin.php
<?php declare (strict_types = 1); namespace app\listener; class WsJoin { /** * 事件监听处理 * * @return mixed */ public function handle($event) { $ws = app('think\swoole\Websocket'); $roomobj = app('think\swoole\websocket\Room'); //当前客户端加入指定 Room $ws -> join($event['room']); //同时加入多个房间 // $ws -> join(['room1','room2']); //指定客户端加入指定 room // $ws -> setSender(2) -> join($event['room']); //获取当前房间所有的 fd $getAllFdInRoom = $roomobj -> getClients($event['room']); //获取指定 fd 加入哪些房间 $getAllRoom = $roomobj -> getRooms($ws -> getSender()); var_dump('当前房间所有 fd:',$getAllFdInRoom); var_dump('当前 fd 加入的所有房间:',$getAllRoom); var_dump('当前请求数据:',$event); $ws -> emit('joincallback','房间加入成功'); } }
app/listener/WsLeave.php
<?php declare (strict_types = 1); namespace app\listener; class WsLeave { /** * 事件监听处理 * * @return mixed */ public function handle($event) { $ws = app('think\swoole\Websocket'); $roomobj = app('think\swoole\websocket\Room'); // 当前客户端离开指定 room $ws -> leave($event['room']); // 同时离开多个 room // $ws -> leave(['one','two']); // 指定客户端离开指定 room // $ws -> setSender(2) -> leave($event['room']); // 获取指定 room 中的所有客户端 fd $getAllFdInRoom = $roomobj -> getClients($event['room']); var_dump('当前房间还剩 fd:',$getAllFdInRoom); $ws -> emit('leavecallback','房间离开成功'); } }
app/listener/RoomTest.php
<?php declare (strict_types = 1); namespace app\listener; class RoomTest { /** * 事件监听处理 * * @return mixed */ public function handle($event) { var_dump($event); $ws = app('think\swoole\Websocket'); //给指定的 room 内所有 fd 发送消息,包括当前客户端,当前客户端没有加入该 room 也可发送 $ws -> to($event['room']) -> emit('roomtestcallback',$event['message']); //指定多个 room 发送消息 //$ws -> to(['one','two']) -> emit('客户端场景值',$event['message']); } }
The above are the front-end HTML page and the back-end join room, leave room and room chat event codes. Let’s start testing.
First enable the Think-Swoole service in the project root directory.
When the browser accesses the wsroot.html or ioroomtest.html page, you can open multiple tabs and simulate multiple clients. We open three first. After the connection is successful, the fds are 1, 2, and 3 respectively. We Let the clients with fd 1 and 2 both join the "one" room, and the client with fd 3 join the "two" room. Since we print all the fds that the user joins in the room in the WsJoin.php join room event, and the user's fd Names of all rooms joined, this information will be printed in the command line, and finally the chat scene value and "Join the room successfully" message will be sent to the current client, which can be viewed in the browser console.
After joining the room, use the client with fd as 1 to enter the message to be sent in the input box of the page. After clicking Send, enter the name of the room to be sent as "one", and then the message will be sent to " one" room, only all clients in the "one" room (fd is 1 and 2) can receive the message.
Now let the client with fd 2 leave the "one" room. Since in the WsLeave.php leave room event, we print the remaining fd after leaving, the information will appear in the command line, visible "one" There is only fd 1 left in the room. fd 1 sends information, but fd 2 cannot receive it.
Regarding other functions of WebSocket-Room, they have been commented in the above code and need to be opened for testing.
H5 WebSocket and SocketIO have already demonstrated the processing of messages in the previous article. The former requires manual parsing of messages returned by the server before they can be used, while the latter will receive messages based on the scene value of the message and do so. Processing can be used directly.
The above is the detailed content of Think-Swoole's WebSocket-Room joins, leaves the room and sends room messages. For more information, please follow other related articles on the PHP Chinese website!