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

Think-Swoole's WebSocket event subscription

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

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:

 websocket = app('\think\swoole\Websocket');
    }
    //连接事件
    public function onConnect()
{
        $this -> websocket -> emit('sendfd',$this -> websocket -> getSender());
    }
    //加入房间
    public function onJoin($event)
{
        $this -> websocket -> join($event['room']);
        $this -> websocket -> emit('joincallback','加入房间成功');
    }
    public function onRoomTest($event)
{
        $this -> websocket -> to($event['room']) -> emit('roomtestcallback',$event['message']);
    }
}

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