Home > PHP Framework > ThinkPHP > Think-Swoole's WebSocket-Room joins, leaves the room and sends room messages

Think-Swoole's WebSocket-Room joins, leaves the room and sends room messages

Release: 2020-10-21 17:17:35
forward
2975 people have browsed it

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'     => [],
    ],
Copy after login

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
Copy after login

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' => [
    ],
];
Copy after login

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(&#39;连接成功&#39;);
    }
    //数据返回的解析
    function mycallback(data){
        var start = data.indexOf(&#39;[&#39;) // 第一次出现的位置
        var start1 = data.indexOf(&#39;{&#39;)
        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(&#39;连接断开&#39;);
    }
    function join()
{
        var room = prompt(&#39;请输入房间号&#39;);
        ws.send(JSON.stringify([&#39;join&#39;,{
            room:room
        }])); //发送的数据必须是 [&#39;test&#39;,数据] 这种格式
    }
    function leave()
{
        var room = prompt(&#39;请输入要离开的房间号&#39;);
        ws.send(JSON.stringify([&#39;leave&#39;,{
            room:room
        }])); //发送的数据必须是 [&#39;test&#39;,数据] 这种格式
    }
    function send()
{
        var message = document.getElementById(&#39;message&#39;).value;
        var room = prompt(&#39;请输入接收消息的房间号&#39;)
        ws.send(JSON.stringify([&#39;RoomTest&#39;,{
            message:message,
            room:room
        }])); //发送的数据必须是 [&#39;test&#39;,数据] 这种格式
    }
</script>
</body>
</html>
Copy after login

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: [&#39;websocket&#39;]});
    socket.on(&#39;connect&#39;, function(){
        console.log(&#39;connect success&#39;);
    });
    socket.on(&#39;close&#39;,function(){
       console.log(&#39;connect close&#39;)
    });
    //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(&#39;请输入房间号&#39;);
        socket.emit(&#39;join&#39;,{
            room : room
        });
    }
    function leave()
{
        var room = prompt(&#39;请输入要离开的房间号&#39;);
        socket.emit(&#39;leave&#39;,{
            room : room
        });
    }
    function send()
{
        var message = document.getElementById(&#39;message&#39;).value;
        var room = prompt(&#39;请输入接收消息的房间号&#39;)
        socket.emit(&#39;RoomTest&#39;,{
            message : message,
            room : room
        });
    }
</script>
</body>
</html>
Copy after login

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(&#39;think\swoole\Websocket&#39;);
        $roomobj = app(&#39;think\swoole\websocket\Room&#39;);
        //当前客户端加入指定 Room
        $ws -> join($event[&#39;room&#39;]);
        //同时加入多个房间
//        $ws -> join([&#39;room1&#39;,&#39;room2&#39;]);
        //指定客户端加入指定 room
//        $ws -> setSender(2) -> join($event[&#39;room&#39;]);
        //获取当前房间所有的 fd
        $getAllFdInRoom = $roomobj -> getClients($event[&#39;room&#39;]);
        //获取指定 fd 加入哪些房间
        $getAllRoom = $roomobj -> getRooms($ws -> getSender());
        var_dump(&#39;当前房间所有 fd:&#39;,$getAllFdInRoom);
        var_dump(&#39;当前 fd 加入的所有房间:&#39;,$getAllRoom);
        var_dump(&#39;当前请求数据:&#39;,$event);
        $ws -> emit(&#39;joincallback&#39;,&#39;房间加入成功&#39;);
    }
}
Copy after login

app/listener/WsLeave.php

<?php
declare (strict_types = 1);
namespace app\listener;
class WsLeave
{
    /**
     * 事件监听处理
     *
     * @return mixed
     */
    public function handle($event)
{
        $ws = app(&#39;think\swoole\Websocket&#39;);
        $roomobj = app(&#39;think\swoole\websocket\Room&#39;);
        // 当前客户端离开指定 room
        $ws -> leave($event[&#39;room&#39;]);
        // 同时离开多个 room
//        $ws -> leave([&#39;one&#39;,&#39;two&#39;]);
        // 指定客户端离开指定 room
//        $ws -> setSender(2) -> leave($event[&#39;room&#39;]);
        // 获取指定 room 中的所有客户端 fd
        $getAllFdInRoom = $roomobj -> getClients($event[&#39;room&#39;]);
        var_dump(&#39;当前房间还剩 fd:&#39;,$getAllFdInRoom);
        $ws -> emit(&#39;leavecallback&#39;,&#39;房间离开成功&#39;);
    }
}
Copy after login

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(&#39;think\swoole\Websocket&#39;);
        //给指定的 room 内所有 fd 发送消息,包括当前客户端,当前客户端没有加入该 room 也可发送
        $ws -> to($event[&#39;room&#39;]) -> emit(&#39;roomtestcallback&#39;,$event[&#39;message&#39;]);
        //指定多个 room 发送消息
        //$ws -> to([&#39;one&#39;,&#39;two&#39;]) -> emit(&#39;客户端场景值&#39;,$event[&#39;message&#39;]);
    }
}
Copy after login

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!

Related labels:
source:阿dai哥
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template