webman定时器发送SSE数据,加了判断,就发送不了

六神花露水

问题描述

额,下面代码 客户端只能收到 $emptyEvents 数据,一直收不到 $endpointEvents 的数据,如果把if 和 else 的代码对调,那么客户端能收到$endpointEvents 但是收不到空包$emptyEvents数据

这是为何

            $id = Timer::add(1, function () use ($connection, &$id, $clientId) {
                // 连接关闭时,清除定时器
                if ($connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
                    dump("init关闭连接");
                    Timer::del($id);
                }
                if (empty(Mcp::$connections[$clientId])) {
                    Mcp::$connections[$clientId] = $connection;
                    $endpointEvents = new ServerSentEvents(['event' => 'endpoint', 'data' => '/mcp/message?clientId=' . $clientId, 'id' => 1]);
                    dump("-------sse-------$clientId----------------");
                    $connection->send($endpointEvents);
                } else {
                    $emptyEvents = new ServerSentEvents([]);
                    $connection->send($emptyEvents);
                }
            });
687 2 0
2个回答

lsmir2

为什么不输出 $connection->getStatus() 看下是什么呢

  • 暂无评论
wzj177

使用 $sentCount 记录已发送次数,第一次回调不检查连接状态:

$sentCount = 0;

// 第一次发送前不检查连接状态,让连接先建立
if ($sentCount > 0 && $connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
Timer::del($timerId);
return;
}

这样可以绕过 webman 框架中 return response() 后连接状态尚未建立的问题。

逻辑流程:

  1. 第一次 Timer 回调($sentCount = 0):跳过状态检查,直接发送数据
  2. 后续 Timer 回调($sentCount > 0):检查连接状态,断开则清理定时器
  3. 每次发送后:$sentCount++
  • 暂无评论
🔝