You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.7 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CoreAgent.ProtocolClient.Enums;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
namespace CoreAgent.ProtocolClient.ProtocolWsClient
{
public partial class ProtocolWsClient
{
#region 事件声明
public event EventHandler? ConnectionOpened;
public event EventHandler? ConnectionClosed;
public event EventHandler<string>? ConnectionError;
public event EventHandler<JObject>? MessageReceived;
public event EventHandler<JObject>? StatsReceived;
public event EventHandler<ClientState>? StateChanged;
#endregion
#region 事件订阅
private void SubscribeToEvents()
{
_messageManager.ConnectionOpened += OnConnectionOpened;
_messageManager.ConnectionClosed += OnConnectionClosed;
_messageManager.ConnectionError += OnConnectionError;
_messageManager.MessageReceived += OnMessageReceived;
_authManager.Authenticated += (s, e) => OnSocketReady();
_statsManager.StatsReceived += (s, e) => StatsReceived?.Invoke(s, e);
}
#endregion
#region 事件处理方法
private void OnConnectionOpened(object? sender, EventArgs e)
{
_logger.LogInformation($"[{_config.Name}] WebSocket连接已打开");
_statsManager.SetConnectionState(true);
StopTimers();
_readyTimer = new Timer(_ => _authManager.HandleReadyMessage(), null, 2500, Timeout.Infinite);
ConnectionOpened?.Invoke(this, EventArgs.Empty);
}
private void OnConnectionClosed(object? sender, EventArgs e)
{
_logger.LogWarning($"[{_config.Name}] WebSocket连接已关闭");
_statsManager.SetConnectionState(false);
ConnectionClosed?.Invoke(this, EventArgs.Empty);
StopTimers();
_isReady = false;
_authManager.Reset();
_protocolLogProcessor.Stop();
_messageManager.ResetLogGetId();
if (State == ClientState.Connected) { }
if (_config.Enabled && State != ClientState.Stop)
{
_logger.LogInformation("启动重连定时器");
SetState(ClientState.Error);
_reconnectTimer = new Timer(_ => Start(), null, _config.ReconnectDelay, Timeout.Infinite);
}
}
private void OnConnectionError(object? sender, string error)
{
_logger.LogError($"[{_config.Name}] WebSocket连接错误: {error}");
SetState(ClientState.Error);
ConnectionError?.Invoke(this, error);
}
#endregion
}
}