额,下面代码 客户端只能收到 $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);
}
});
为什么不输出 $connection->getStatus() 看下是什么呢
使用 $sentCount 记录已发送次数,第一次回调不检查连接状态:
$sentCount = 0;
// 第一次发送前不检查连接状态,让连接先建立
if ($sentCount > 0 && $connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
Timer::del($timerId);
return;
}
这样可以绕过 webman 框架中 return response() 后连接状态尚未建立的问题。
逻辑流程: