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.

95 lines
2.4 KiB

using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocket4Net;
namespace CoreAgent.ProtocolClient.Managers.WebSocketMgr
{
/// <summary>
/// WebSocket消息管理器 - 处理WebSocket连接和消息传输
/// </summary>
public partial class WebSocketMessageManager : IDisposable
{
#region 私有字段
// WebSocket连接实例
private WebSocket? _webSocket;
// 客户端名称
private readonly string _clientName;
// 日志记录器
private readonly ILogger<WebSocketMessageManager> _logger;
// 消息ID管理器
private readonly MessageIdManager _messageIdManager;
// 消息队列
private readonly BlockingCollection<JObject> _messageFifo;
// 消息延迟发送定时器
private Timer? _messageDeferTimer;
// 释放标志
private bool _disposed;
// 同步锁对象
private readonly object _lockObject = new object();
#endregion
#region 事件
// 连接打开事件
public event EventHandler? ConnectionOpened;
// 连接关闭事件
public event EventHandler? ConnectionClosed;
// 连接错误事件
public event EventHandler<string>? ConnectionError;
// 消息接收事件
public event EventHandler<JObject>? MessageReceived;
// 消息发送事件
public event EventHandler<JObject>? MessageSent;
#endregion
#region 属性
/// <summary>
/// 是否已连接
/// </summary>
public bool IsConnected => _webSocket?.State == WebSocketState.Open;
/// <summary>
/// WebSocket状态
/// </summary>
public WebSocketState State => _webSocket?.State ?? WebSocketState.None;
/// <summary>
/// 是否已释放
/// </summary>
public bool IsDisposed => _disposed;
/// <summary>
/// 消息队列数量
/// </summary>
public int MessageQueueCount => _messageFifo.Count;
/// <summary>
/// 消息ID管理器
/// </summary>
public MessageIdManager MessageIdManager => _messageIdManager;
#endregion
}
}