using BBWY.Common.Models; using Fleck; using Newtonsoft.Json.Linq; using System; using System.Collections.Concurrent; namespace BBWY.WebSocket.Server.Helpers { public class WSHelper : IDenpendency { private ConcurrentDictionary bbwySocketPool; private WebSocketServer wsServer; public WSHelper() { } public void Listen() { wsServer = new WebSocketServer("ws://127.0.0.1:35192"); bbwySocketPool = new ConcurrentDictionary(); //开启监听 wsServer.Start(socket => { //注册客户端连接建立事件 socket.OnOpen = () => { Console.WriteLine("建立连接"); if (!string.IsNullOrEmpty(socket.ConnectionInfo.Path) && socket.ConnectionInfo.Path.Contains("bbwy")) { var key = socket.ConnectionInfo.Path.Substring(socket.ConnectionInfo.Path.LastIndexOf("/") + 1); bbwySocketPool.TryRemove(key, out _); bbwySocketPool.TryAdd(key, socket); //将bbwy当前客户端连接对象放入连接池中 } }; //注册客户端连接关闭事件 socket.OnClose = () => { if (!string.IsNullOrEmpty(socket.ConnectionInfo.Path) && socket.ConnectionInfo.Path.Contains("bbwy")) { var key = socket.ConnectionInfo.Path.Substring(socket.ConnectionInfo.Path.LastIndexOf("/") + 1); bbwySocketPool.TryRemove(key, out _); } }; //注册客户端发送信息事件 socket.OnMessage = message => { Console.WriteLine($"收到webSocket消息:{message}"); socket.Close(); try { var j = JObject.Parse(message); if (!string.IsNullOrEmpty(j.Value("user"))) { if (bbwySocketPool.TryGetValue(j.Value("user"), out IWebSocketConnection bbwySocket)) { _ = bbwySocket.Send(message); } } } catch { } }; }); } } }