public override void DisConnect(IPEndPoint iPEndPoint) { lock (ClientInstance) { string key = iPEndPoint.ToString(); if (ClientInstance.TryGetValue(key, out Instance instance)) { WSInstance wsInstance = (WSInstance)instance; wsInstance.Dispose(); ClientInstance.Remove(key); } } }
public WebSocket(SocketServer socketServer, int port) : base(socketServer) { _server = new WebSocketServer(port) { WaitTime = TimeSpan.FromSeconds(1) }; _server.Log.KnownFatal = new List <string>() { "The header of a frame cannot be read from the stream.", "Object name: 'System.Net.Sockets.NetworkStream'." }; _server.WebSocketServices.AddService <WSPeer>("/WebSocket", peer => { peer._OnOpen += () => { IPEndPoint iPEndPoint = peer.Context.UserEndPoint; string clientIp = iPEndPoint.ToString(); if (ClientInstance.ContainsKey(clientIp)) { ClientInstance.Remove(clientIp); } // 建立玩家peer實體 ClientNode cNode = _SocketServer.GetPeer(this, iPEndPoint, _SocketServer); try { //註冊到 mListener 中,讓他的 Receive 功能能被叫 WSInstance instance = new WSInstance(cNode, peer); //註冊到 mListener 中,讓他的 Receive 功能能被叫 ClientInstance.Add(clientIp, instance); //成功加入後傳送 Connect 事件給 Client peer.SendBytes(new byte[] { 1 }); cNode.Initialize(); } catch (Exception e) { Printer.WriteError($"Accept connection failed : {e.Message}\n{e.StackTrace}"); } }; peer._OnMessage += packet => { if (ClientInstance.TryGetValue(peer.Context.UserEndPoint.ToString(), out Instance instance)) { WSInstance client = (WSInstance)instance; client.PassData(packet); } }; peer._OnClose += e => { DisConnect(peer.Context.UserEndPoint); }; peer._OnError += e => { DisConnect(peer.Context.UserEndPoint); }; }); }