Home >PHP Framework >ThinkPHP >Think-Swoole's WebSocket event subscription

Think-Swoole's WebSocket event subscription

藏色散人
藏色散人forward
2020-10-26 14:15:122429browse

Through the previous example, if you follow the previous event listening method, the server needs to create each corresponding event for each scene event on the client. If there are too many events, there will be a lot of them in the app/listener directory. File (actually not a bad phenomenon), event subscription is to solve this problem and write all events in a file.

The following uses event subscription to process events

First, you need to comment out the events that were previously listened to in app/event.php, and then create a listening event: php think make:listener SubTest.

Then configure the newly created listening file in websocket => subscribe in the config/swoole.php configuration:

'websocket'  => [
        .
        .
        .
        'listen'        => [],
        'subscribe'     => [
           \app\listener\SubTest::class
        ],
],

Define the events that need to be listened to in app/listener/SubTest.php:

<?php
declare (strict_types = 1);
namespace app\listener;
class SubTest
{
    protected $websocket = null;
    public function __construct()
{
        $this -> websocket = app(&#39;\think\swoole\Websocket&#39;);
    }
    //连接事件
    public function onConnect()
{
        $this -> websocket -> emit(&#39;sendfd&#39;,$this -> websocket -> getSender());
    }
    //加入房间
    public function onJoin($event)
{
        $this -> websocket -> join($event[&#39;room&#39;]);
        $this -> websocket -> emit(&#39;joincallback&#39;,&#39;加入房间成功&#39;);
    }
    public function onRoomTest($event)
{
        $this -> websocket -> to($event[&#39;room&#39;]) -> emit(&#39;roomtestcallback&#39;,$event[&#39;message&#39;]);
    }
}

Naming convention for methods to listen to events: on event scene identifier (hump naming)

Tested with the previous front-end page, everything is normal.

The above is the detailed content of Think-Swoole's WebSocket event subscription. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:阿dai哥. If there is any infringement, please contact admin@php.cn delete