-
Notifications
You must be signed in to change notification settings - Fork 6
3.Websocket room
l1n6yun edited this page Jan 7, 2020
·
1 revision
php think make:listener RoomLeave
php think make:listener RoomJoin
RoomJoin.php
<?php
declare (strict_types = 1);
namespace app\listener;
use think\Container;
use think\swoole\Websocket;
class RoomJoin
{
private $websocket;
/**
* WebsocketTest constructor.
* @param Container $container
*/
public function __construct(Container $container)
{
$this->websocket = $container->make(Websocket::class);
}
/**
* 事件监听处理
* @param $event
*/
public function handle($event)
{
$this->websocket->join($event['room']);
$fd = $this->websocket->getSender();
$this->websocket->to($event['room'])->emit("chatMessage", ['msg' => "用户({$fd})加入了房间({$event['room']})"]);
}
}
RoomLeave.php
<?php
declare (strict_types = 1);
namespace app\listener;
use think\Container;
use think\swoole\Websocket;
class RoomLeave
{
private $websocket;
/**
* WebsocketTest constructor.
* @param Container $container
*/
public function __construct(Container $container)
{
$this->websocket = $container->make(Websocket::class);
}
/**
* 事件监听处理
* @param $event
*/
public function handle($event)
{
$this->websocket->leave($event['room']);
$fd = $this->websocket->getSender();
$this->websocket->to($event['room'])->emit("chatMessage", ['msg' => "用户({$fd})退出了房间({$event['room']})"]);
}
}
'listen' => [
'test' => \app\listener\WebsocketTest::class,
'join' => \app\listener\RoomJoin::class,
'leave' => \app\listener\RoomLeave::class,
]
// 对指定room进行群发
$fd = $this->websocket->getSender();
$this->websocket->to('room1')->emit("chatMessage", ['msg' => "用户({$fd}):{$event['msg']}"]);
// 指定客户端发送
$this->websocket->setSender(1)->emit("chatMessage", ['msg' => "用户({$fd}):{$event['msg']}"]);
// 获取当前客户端fd
$this->websocket->getSender();
// 关闭指定客户端连接,参数为fd,默认为当前链接
$this->websocket->close();