| | |
| | | public static class WebSocketServer |
| | | { |
| | | private static List<IWebSocketConnection> _connections = new List<IWebSocketConnection>(); |
| | | // 套接字连接 与 用户标识符 字典 |
| | | private static ConcurrentDictionary<IWebSocketConnection, string> _NameConnectionDict = new ConcurrentDictionary<IWebSocketConnection, string>(); |
| | | |
| | | private static Fleck.WebSocketServer _server; |
| | | // 内置定时器(用于定时查询数据库并推送) |
| | | private static System.Timers.Timer _pushTimer; |
| | | // 内置定时器(用于发送心跳信号) |
| | | private static System.Timers.Timer _pushTimerBeat; |
| | | // 300000 |
| | | private static readonly int _pushInterval = 10000; |
| | | private static readonly int _pushInterval = 300000; // 每5分钟发送一次消息 |
| | | |
| | | /// <summary> |
| | | /// 启动 WebSocket 服务(监听 18080 端口) |
| | | /// 启动 WebSocket 服务(监听 8089 端口) |
| | | /// </summary> |
| | | public static void Start() |
| | | { |
| | |
| | | _pushTimer = new System.Timers.Timer(_pushInterval); |
| | | _pushTimer.AutoReset = false; // 非自动重置,避免并发 |
| | | _pushTimer.Elapsed += OnTimerElapsed; // 绑定静态事件 |
| | | |
| | | _pushTimerBeat = new System.Timers.Timer(30000); |
| | | _pushTimerBeat.AutoReset = false; // 非自动重置,避免并发 |
| | | _pushTimerBeat.Elapsed += BeatSignalSender; // 绑定静态事件 |
| | | |
| | | // 配置 Fleck 服务 |
| | | _server.Start(connection => |
| | |
| | | connection.OnMessage = message => |
| | | { |
| | | Console.WriteLine($"收到消息:{message}"); |
| | | |
| | | // TODO 心跳信号 |
| | | }; |
| | | |
| | | // 客户端断开连接时 |
| | |
| | | { |
| | | _server?.Dispose(); |
| | | _pushTimer?.Stop(); |
| | | _pushTimerBeat?.Stop(); |
| | | |
| | | Console.WriteLine("Fleck WebSocket 服务已停止"); |
| | | } |
| | | |
| | | |
| | | /// <summary> |
| | | /// 静态定时器触发事件 |
| | | /// 静态定时器触发事件 推送 未读消息 |
| | | /// </summary> |
| | | private static void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e) |
| | | { |
| | |
| | | } |
| | | } |
| | | } |
| | | |
| | | // 定时器发送心跳信号 |
| | | private static void BeatSignalSender(object sender, System.Timers.ElapsedEventArgs e) |
| | | { |
| | | try |
| | | { |
| | | foreach (var dictOne in _NameConnectionDict) |
| | | { |
| | | LogService.Write($@"服务端 向 {dictOne.Value} 发送心跳信号"); |
| | | dictOne.Key.SendPing(new byte[0]); |
| | | } |
| | | } |
| | | catch (Exception ex) |
| | | { |
| | | LogService.Write(ex.ToString()); |
| | | return; |
| | | } |
| | | finally |
| | | { |
| | | // 静态定时器手动重启 |
| | | if (_pushTimer != null && !_pushTimer.Enabled) |
| | | { |
| | | _pushTimer.Start(); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | } |