Think-Swoole 教程(九)WebSocket 事件订阅

通过前面的实例中,如果按照之前的事件监听方式,客户端的每个场景事件,服务端都需要创建每个对应的事件,如果事件太多, app/listener 目录下将会有很多的文件(其实也不算什么坏现象),事件订阅就是为了解决这一问题,把所有的事件都写在一个文件中。下面用事件订阅的方式处理事件

首先需要把之前在 app/event.php 监听的事件给注释掉,然后创建一个监听事件:php think make:listener SubTest

然后在 config/swoole.php 配置中的 websocket => subscribe 配置刚创建的监听文件:


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

在 app/listener/SubTest.php 中定义需要监听的事件:

<?php
declare (strict_types = 1);

namespace app\listener;

class SubTest
{
    protected $websocket = null;

    public function __construct()
    {
        $this -> 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']);
    }
}

监听事件的方法命名规范:on+事件场景标识(驼峰命名)

用之前的前端页面进行测试,一切正常。

发表评论

发表回复

沙发空缺中,还不快抢~