Home > PHP Framework > ThinkPHP > body text

Think-Swoole's WebSocket event subscription

Release: 2020-10-26 14:15:12
forward
2389 people have browsed it

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

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;]);
    }
}
Copy after login

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!

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