<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
class WebSocketServer
{
protected $worker;
protected $uidConnections = [];
public function __construct($host = 'workerman.net', $port = 1234)
{
// 创建 WebSocket 服务
$this->worker = new Worker("websocket://$host:$port");
// 设置进程数为 1
$this->worker->count = 1;
// 设置事件回调
$this->worker->onMessage = [$this, 'onMessage'];
$this->worker->onClose = [$this, 'onClose'];
}
// 当有客户端发来消息时执行的回调函数
public function onMessage(TcpConnection $connection, $data)
{
// 判断当前客户端是否已经验证,是否设置了uid
if (!isset($connection->uid)) {
// 未验证时,将第一个包当做uid(为了演示方便,实际应用中应进行更严格的验证)
$connection->uid = $data;
// 保存uid到connection的映射
$this->uidConnections[$connection->uid] = $connection;
类面向对象-Workerman中如何向某个特定客户端发送数据
最新推荐文章于 2025-04-09 00:31:32 发布

3369

被折叠的 条评论
为什么被折叠?



