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

Oct 21, 2020 pm 05:17 PM
think-swoole

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Performance optimization and debugging of TP6 Think-Swoole RPC service Performance optimization and debugging of TP6 Think-Swoole RPC service Oct 12, 2023 am 11:16 AM

Performance optimization and debugging of TP6Think-SwooleRPC service 1. Introduction With the rapid development of the Internet, distributed computing has become an indispensable part of modern software development. In distributed computing, RPC (RemoteProcedureCall, Remote Procedure Call) is a commonly used communication mechanism through which method calls across the network can be implemented. Think-Swoole, as a high-performance PHP framework, can support RPC services well. but

High scalability and distributed deployment of TP6 Think-Swoole RPC service High scalability and distributed deployment of TP6 Think-Swoole RPC service Oct 12, 2023 am 11:07 AM

TP6 (ThinkPHP6) is an open source framework based on PHP, which has the characteristics of high scalability and distributed deployment. This article will introduce how to use TP6 with Swoole extension to build a highly scalable RPC service, and give specific code examples. First, we need to install TP6 and Swoole extensions. Execute the following command in the command line: composerrequiretopthink/thinkpeclinstallswo

Data encryption and identity authentication mechanism of TP6 Think-Swoole RPC service Data encryption and identity authentication mechanism of TP6 Think-Swoole RPC service Oct 12, 2023 am 11:29 AM

Data encryption and identity authentication mechanism of TP6Think-SwooleRPC service With the rapid development of the Internet, more and more applications need to make remote calls to realize data interaction and function calls between different modules. In this context, RPC (RemoteProcedureCall) has become an important communication method. The TP6Think-Swoole framework can implement high-performance RPC services. This article will introduce how to use data encryption and identity authentication.

TP6 Think-Swoole's RPC service and message queue integration and application TP6 Think-Swoole's RPC service and message queue integration and application Oct 12, 2023 am 11:37 AM

Integration and application of TP6Think-Swoole's RPC service and message queue In modern software development, RPC service (RemoteProcedureCall) and message queue are common technical means used to implement service calls and asynchronous message processing in distributed systems. Integrating Think-Swoole components in the TP6 framework can easily implement the functions of RPC services and message queues, and provides concise code examples for developers to understand and apply. 1. RPC

Highly concurrent request processing and scheduling of TP6 Think-Swoole RPC service Highly concurrent request processing and scheduling of TP6 Think-Swoole RPC service Oct 12, 2023 pm 12:33 PM

Highly concurrent request processing and scheduling of TP6Think-SwooleRPC service With the continuous development of Internet technology, concurrent request processing and scheduling of network applications has become an important challenge. In the TP6 framework, the Think-Swoole extension can be used to implement high-concurrency request processing and scheduling of the RPC (RemoteProcedureCall) service. This article will introduce how to build a Think-Swoole-based RPC service in the TP6 framework and provide

Security protection and authorization verification of TP6 Think-Swoole RPC service Security protection and authorization verification of TP6 Think-Swoole RPC service Oct 12, 2023 pm 01:15 PM

Security protection and authorization verification of TP6Think-SwooleRPC service With the rise of cloud computing and microservices, remote procedure call (RPC) has become an essential part of developers' daily work. When developing RPC services, security protection and authorization verification are very important to ensure that only legitimate requests can access and call the service. This article will introduce how to implement security protection and authorization verification of RPC services in the TP6Think-Swoole framework. 1. Basic concepts of RPC services

TP6 RPC service and microservice architecture practice cases built by Think-Swoole TP6 RPC service and microservice architecture practice cases built by Think-Swoole Oct 12, 2023 pm 12:04 PM

Introduction to the practical case of RPC service and microservice architecture built by TP6Think-Swoole: With the rapid development of the Internet and the expansion of business scale, the traditional monolithic architecture can no longer meet the needs of large-scale business scenarios. Therefore, the microservice architecture came into being. In the microservice architecture, the RPC (RemoteProcedureCall) service is an important way to achieve communication between services. Through RPC services, various microservices can call each other conveniently and efficiently. In this article

Performance testing and performance tuning of TP6 Think-Swoole RPC service Performance testing and performance tuning of TP6 Think-Swoole RPC service Oct 12, 2023 pm 02:19 PM

Performance testing and performance tuning of TP6Think-SwooleRPC service 1. Introduction With the rapid development of the Internet, the application of distributed systems is becoming more and more widespread. In distributed systems, RPC (Remote Procedure Call) is a common communication mechanism, which allows services on different nodes to call each other and achieve collaborative work in distributed systems. In the TP6 framework, Think-Swoole, as a high-performance Swoole driver, provides convenient RPC service support. This article mainly introduces T

See all articles