Browse Source

完全修复 - WebSocketTransport 现在可以安全地多次连接和断开

feature/protocol-log-Perfect
root 4 months ago
parent
commit
4b6b523b60
  1. 21
      CoreAgent.WebSocketTransport/Services/WebSocketTransport.cs

21
CoreAgent.WebSocketTransport/Services/WebSocketTransport.cs

@ -76,17 +76,27 @@ public class WebSocketTransport : IWebSocketTransport
await _connectionSemaphore.WaitAsync(cancellationToken);
try
{
if (_isConnected)
// 检查连接状态,包括 WebSocket 连接状态
if (_isConnected && _connection.IsConnected)
{
_logger.LogInformation("WebSocket 已连接,跳过重复连接");
return;
}
// 如果状态不一致,强制重置状态
if (_isConnected && !_connection.IsConnected)
{
_logger.LogWarning("连接状态不一致,强制重置状态");
_isConnected = false;
}
await ConnectInternalAsync(cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "连接 WebSocket 服务器失败: {Url}", _config.Url);
// 确保连接失败时状态正确
_isConnected = false;
throw;
}
finally
@ -148,6 +158,13 @@ public class WebSocketTransport : IWebSocketTransport
_logger.LogInformation("所有后台任务已完成");
}
// 清理后台任务引用
_sendTask = null;
_receiveTask = null;
_heartbeatTask = null;
_reconnectTask = null;
_logger.LogDebug("后台任务引用已清理");
// 关闭连接
try
{
@ -174,7 +191,9 @@ public class WebSocketTransport : IWebSocketTransport
// 不抛出异常,确保不影响连接关闭流程
}
// 重置所有状态
_isConnected = false;
_reconnectAttempts = 0;
// 重新创建 CancellationTokenSource 以支持下次连接
RecreateCancellationTokenSource();

Loading…
Cancel
Save