using CoreAgent.ProtocolClient.Models; using CoreAgent.ProtocolClient.ProtocolEngineCore; using CoreAgent.ProtocolClient.ProtocolWsClient; using CoreAgent.ProtocolClient.Interfaces; using Microsoft.Extensions.Logging; namespace CoreAgent.Infrastructure.Services.Network { /// /// 协议WebSocket客户端管理器 /// 负责启动和停止所有协议客户端 /// public class ProtocolWsClientManager : IProtocolWsClientManager { private readonly ILogger _logger; private readonly IProtocolLogObserver _protocolLogObserver; private readonly Dictionary _clients; private readonly ILoggerFactory _loggerFactory; private readonly object _lock = new object(); private bool _disposed = false; public ProtocolWsClientManager( ILogger logger, IProtocolLogObserver protocolLogObserver, ILoggerFactory loggerFactory) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _protocolLogObserver = protocolLogObserver ?? throw new ArgumentNullException(nameof(protocolLogObserver)); _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); _clients = new Dictionary(); } /// /// 创建ProtocolWsClient实例 /// /// 协议客户端配置 /// ProtocolWsClient实例 private ProtocolWsClient CreateProtocolWsClient(ProtocolClientConfig config) { if (config == null) throw new ArgumentNullException(nameof(config)); if (string.IsNullOrEmpty(config.Name)) throw new ArgumentException("配置名称不能为空", nameof(config)); _logger.LogInformation("创建ProtocolWsClient实例: {ClientName}", config.Name); return new ProtocolWsClient(config, _loggerFactory, _protocolLogObserver); } /// /// 启动所有协议客户端 /// /// 协议客户端配置数组 /// 是否所有客户端都成功启动 public bool StartAllClients(ProtocolClientConfig[] configs) { ThrowIfDisposed(); if (configs == null || configs.Length == 0) { _logger.LogWarning("没有可用的协议客户端配置"); return false; } lock (_lock) { _logger.LogInformation("开始启动所有协议客户端,配置数量: {ConfigCount}", configs.Length); var startedCount = 0; var failedCount = 0; foreach (var config in configs) { try { if (!_clients.ContainsKey(config.Name)) { var client = CreateProtocolWsClient(config); _clients[config.Name] = client; } var existingClient = _clients[config.Name]; existingClient.Start(); startedCount++; _logger.LogInformation("启动协议客户端成功: {ClientName}", config.Name); } catch (Exception ex) { failedCount++; _logger.LogError(ex, "启动协议客户端失败: {ClientName}", config.Name); } } var allStarted = startedCount == configs.Length; _logger.LogInformation("协议客户端启动完成 - 成功: {StartedCount}, 失败: {FailedCount}, 全部启动: {AllStarted}", startedCount, failedCount, allStarted); return allStarted; } } /// /// 检查所有协议客户端连接状态 /// /// 超时时间(秒),默认10秒 /// 是否所有客户端都已连接 public bool CheckAllClientsConnection(int timeoutSeconds = 10) { ThrowIfDisposed(); if (timeoutSeconds <= 0) { _logger.LogWarning("超时时间必须大于0,使用默认值10秒"); timeoutSeconds = 10; } lock (_lock) { if (_clients.Count == 0) { _logger.LogWarning("没有运行中的协议客户端"); return false; } _logger.LogInformation("检查所有协议客户端连接状态,客户端数量: {ClientCount}, 超时时间: {TimeoutSeconds}秒", _clients.Count, timeoutSeconds); var startTime = DateTime.UtcNow; var timeout = TimeSpan.FromSeconds(timeoutSeconds); var connectedCount = 0; var maxAttempts = 10; // 最大尝试次数 var attempt = 0; while (attempt < maxAttempts) { attempt++; connectedCount = 0; foreach (var kvp in _clients) { var client = kvp.Value; if (client.IsConnected) { connectedCount++; } _logger.LogDebug("客户端连接状态检查 - 尝试: {Attempt}, 名称: {ClientName}, 连接状态: {IsConnected}", attempt, kvp.Key, client.IsConnected); } var allConnected = connectedCount == _clients.Count; if (allConnected) { var elapsed = DateTime.UtcNow - startTime; _logger.LogInformation("协议客户端连接状态检查完成 - 已连接: {ConnectedCount}, 总数量: {TotalCount}, 全部连接: {AllConnected}, 耗时: {Elapsed}ms", connectedCount, _clients.Count, allConnected, elapsed.TotalMilliseconds.ToString("F2")); return true; } // 检查是否超时 if (DateTime.UtcNow - startTime > timeout) { var elapsed = DateTime.UtcNow - startTime; _logger.LogWarning("协议客户端连接状态检查超时 - 已连接: {ConnectedCount}, 总数量: {TotalCount}, 耗时: {Elapsed}ms, 超时时间: {TimeoutSeconds}秒", connectedCount, _clients.Count, elapsed.TotalMilliseconds.ToString("F2"), timeoutSeconds); return false; } // 等待一段时间后重试 if (attempt < maxAttempts) { var waitTime = Math.Min(1000, timeoutSeconds * 100); // 等待时间,最大1秒 Thread.Sleep(waitTime); } } var finalElapsed = DateTime.UtcNow - startTime; _logger.LogWarning("协议客户端连接状态检查达到最大尝试次数 - 已连接: {ConnectedCount}, 总数量: {TotalCount}, 耗时: {Elapsed}ms", connectedCount, _clients.Count, finalElapsed.TotalMilliseconds.ToString("F2")); return false; } } /// /// 停止所有协议客户端 /// /// 是否所有客户端都成功停止并断开连接 public bool StopAllClients() { lock (_lock) { if (_clients.Count == 0) { _logger.LogInformation("没有运行中的协议客户端"); return true; } _logger.LogInformation("开始停止所有协议客户端,客户端数量: {ClientCount}", _clients.Count); var stoppedCount = 0; var failedCount = 0; var disconnectedCount = 0; foreach (var kvp in _clients) { try { var client = kvp.Value; var wasConnected = client.IsConnected; client.Stop(); stoppedCount++; // 检查连接状态 if (!client.IsConnected) { disconnectedCount++; } _logger.LogInformation("停止协议客户端成功: {ClientName}, 原连接状态: {WasConnected}, 当前连接状态: {IsConnected}", kvp.Key, wasConnected, client.IsConnected); } catch (Exception ex) { failedCount++; _logger.LogError(ex, "停止协议客户端失败: {ClientName}", kvp.Key); } } var allDisconnected = disconnectedCount == _clients.Count; _logger.LogInformation("协议客户端停止完成 - 成功: {StoppedCount}, 失败: {FailedCount}, 已断开: {DisconnectedCount}, 全部断开: {AllDisconnected}", stoppedCount, failedCount, disconnectedCount, allDisconnected); return allDisconnected; } } /// /// 获取所有客户端状态 /// public void GetAllClientsStatus() { lock (_lock) { if (_clients.Count == 0) { _logger.LogInformation("没有运行中的协议客户端"); return; } _logger.LogInformation("获取所有协议客户端状态,客户端数量: {ClientCount}", _clients.Count); foreach (var kvp in _clients) { var client = kvp.Value; _logger.LogInformation("客户端状态 - 名称: {ClientName}, 连接状态: {IsConnected}, 客户端状态: {State}", kvp.Key, client.IsConnected, client.State); } } } /// /// 释放所有客户端资源 /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// 释放资源 /// /// 是否正在释放托管资源 protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { lock (_lock) { StopAllClients(); var disposedCount = 0; var failedCount = 0; foreach (var client in _clients.Values) { try { client.Dispose(); disposedCount++; } catch (Exception ex) { failedCount++; _logger.LogError(ex, "释放客户端资源失败"); } } _clients.Clear(); _logger.LogInformation("协议客户端管理器释放完成 - 成功: {DisposedCount}, 失败: {FailedCount}", disposedCount, failedCount); } } _disposed = true; } /// /// 检查是否已释放 /// private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(ProtocolWsClientManager)); } } } }