|
|
|
@ -22,7 +22,7 @@ public class WebSocketTransport : IWebSocketTransport |
|
|
|
private readonly IEnumerable<IMessageMiddleware> _middlewares; |
|
|
|
private readonly WebSocketConfig _config; |
|
|
|
private readonly IMessageChannelManager _channelManager; |
|
|
|
private readonly CancellationTokenSource _cancellationTokenSource; |
|
|
|
private CancellationTokenSource _cancellationTokenSource; |
|
|
|
private readonly SemaphoreSlim _connectionSemaphore; |
|
|
|
|
|
|
|
// 连接状态管理
|
|
|
|
@ -175,6 +175,10 @@ public class WebSocketTransport : IWebSocketTransport |
|
|
|
} |
|
|
|
|
|
|
|
_isConnected = false; |
|
|
|
|
|
|
|
// 重新创建 CancellationTokenSource 以支持下次连接
|
|
|
|
RecreateCancellationTokenSource(); |
|
|
|
|
|
|
|
_logger.LogInformation("WebSocket 连接关闭完成"); |
|
|
|
} |
|
|
|
catch (Exception ex) |
|
|
|
@ -189,6 +193,55 @@ public class WebSocketTransport : IWebSocketTransport |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// 重新创建 CancellationTokenSource
|
|
|
|
/// </summary>
|
|
|
|
private void RecreateCancellationTokenSource() |
|
|
|
{ |
|
|
|
try |
|
|
|
{ |
|
|
|
// 释放旧的 CancellationTokenSource
|
|
|
|
_cancellationTokenSource?.Dispose(); |
|
|
|
|
|
|
|
// 创建新的 CancellationTokenSource
|
|
|
|
_cancellationTokenSource = new CancellationTokenSource(); |
|
|
|
|
|
|
|
_logger.LogDebug("CancellationTokenSource 已重新创建,支持下次连接"); |
|
|
|
} |
|
|
|
catch (Exception ex) |
|
|
|
{ |
|
|
|
_logger.LogError(ex, "重新创建 CancellationTokenSource 失败"); |
|
|
|
// 即使失败也要创建新的实例,避免影响下次连接
|
|
|
|
_cancellationTokenSource = new CancellationTokenSource(); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// 检查并确保 CancellationTokenSource 可用
|
|
|
|
/// </summary>
|
|
|
|
private void EnsureCancellationTokenSourceAvailable() |
|
|
|
{ |
|
|
|
try |
|
|
|
{ |
|
|
|
// 检查 CancellationTokenSource 是否为 null 或已被取消
|
|
|
|
if (_cancellationTokenSource == null || _cancellationTokenSource.IsCancellationRequested) |
|
|
|
{ |
|
|
|
_logger.LogDebug("CancellationTokenSource 不可用,重新创建新实例"); |
|
|
|
RecreateCancellationTokenSource(); |
|
|
|
} |
|
|
|
else |
|
|
|
{ |
|
|
|
_logger.LogDebug("CancellationTokenSource 状态正常,无需重新创建"); |
|
|
|
} |
|
|
|
} |
|
|
|
catch (Exception ex) |
|
|
|
{ |
|
|
|
_logger.LogError(ex, "检查 CancellationTokenSource 状态时发生异常,强制重新创建"); |
|
|
|
// 发生异常时强制重新创建
|
|
|
|
RecreateCancellationTokenSource(); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// 内部连接方法
|
|
|
|
/// </summary>
|
|
|
|
@ -208,7 +261,10 @@ public class WebSocketTransport : IWebSocketTransport |
|
|
|
UpdateHeartbeat(); |
|
|
|
_logger.LogDebug("连接状态已更新,重连次数重置为 0"); |
|
|
|
|
|
|
|
// 4. 启动后台任务
|
|
|
|
// 4. 检查并确保 CancellationTokenSource 可用
|
|
|
|
EnsureCancellationTokenSourceAvailable(); |
|
|
|
|
|
|
|
// 5. 启动后台任务
|
|
|
|
StartBackgroundTasks(); |
|
|
|
|
|
|
|
_logger.LogInformation("WebSocket 连接成功建立,所有后台任务已启动"); |
|
|
|
|