thinkphp6 websocket订阅事件

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

注释原先的配置防止冲突
在这里插入图片描述
增加订阅事件配置
在这里插入图片描述
订阅事件中的代码

<?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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值