1. 对比一下前面说过的2.0(可能是2.0)的配置来讲。其实就是路由(事件监听)那块有改动。
2. 先看配置文件
'websocket' => [
'enable' => true,
'handler' => Handler::class,
'parser' => Parser::class,
'ping_interval' => 25000,
'ping_timeout' => 60000,
'room' => [
'type' => 'redis',
'table' => [
'room_rows' => 4096,
'room_size' => 2048,
'client_rows' => 8192,
'client_size' => 2048,
],
'redis' => [
'host'=>'redis',
'prefix'=>'ws'
],
],
'listen' => [
//事件监听 一个socket事件对应一个php文件 文件类中 实现handle方法
//这种方式 事件一多 要配置许多文件,但精准快速
'login'=>Login::class
],
'subscribe' => [
//事件订阅 一个文件中可以写多个socket事件 php类方法对应socket事件名 类方法前+on
//这种方式是观察者模式
'app\listener\User'
],
],3. 再上两种方式的代码第一种
<?php
namespace app\listener;
use think\Container;
use think\swoole\Websocket;
class Login{
/**
* Undocumented variable
*
* @var \think\swoole\Websocket
* @author 秋月 414111907@qq.com
*/
public $websocket = null;
public function __construct(Container $container){
$this->websocket = $container->make(Websocket::class);
}
public function handle($event){
//dump($this->websocket->getFds());
// dump($event);
// dump($this->websocket->getSender());
//$this->websocket->emit("ddd",["aaa"=>1]);
}
}第二种<?php
namespace app\listener;
use think\Container;
use think\swoole\Websocket;
class User{
/**
* Undocumented variable
*
* @var Websocket
* @author 秋月 414111907@qq.com
*/
public $websocket = null;
public function __construct(Container $container){
$this->websocket = $container->make(Websocket::class);
}
public function onLogin(){
$this->websocket->emit("login",['mid'=>123]);
}
public function onPay(){
$this->websocket->emit("pay",['no'=>1233453452421]);
}
}注: tp6 swoole websocket这块难用,主要是没有手册的原因。有手册说明一下,很快就能上手。另外再参照一下tp6手册中的事件,很快就能明白了https://www.kancloud.cn/manual/thinkphp6_0/1037492
有兴趣的还可以再去看下源码的实现
主要是这个文件
vendor\topthink\think-swoole\src\concerns\InteractsWithWebsocket.php
