thinkphp6 websocket订阅事件

如果按照之前的方法,文件会有很多,那么怎么解决这个问题呢
一种方式是采用事件订阅的方式,可以把多个事件写在一个文件中。
具体操作:
SubTest 名称自定义
建立订阅事件
php think make:listener SubTest

注释原先的配置防止冲突
thinkphp6 websocket订阅事件_第1张图片
增加订阅事件配置
thinkphp6 websocket订阅事件_第2张图片
订阅事件中的代码

<?php
declare (strict_types = 1);

namespace app\listener;

use think\swoole\Websocket;

class SubTest
{
    protected  $websocket = null;

	//这里使用了连接websocket的另一种方式  管理类
    public function __construct(\think\Container $container)
    {
        //$this->websocket = app('think\swoole\Websocket');
        $this->websocket = $container->make(Websocket::class);
    }
	//需要注意的是方法前面要加on
    public function onConnect(){
        $this->websocket ->emit('sendfd', $this -> websocket->getsender());
    }

    public function onJoin($event){
        $this->websocket->join($event['room']);
        $this->websocket->emit('joincall', "这是我的加入成功");
    }

}

知识积累
html原生的websocket断开是不能自动连接的可以通过写一个方法实现自动连接
但是socket.io断开的话自身是会自动给连接的
所以建议使用socket.io

你可能感兴趣的:(thinkphp6 websocket订阅事件)