/// <summary> /// 移除一个客户端 /// </summary> /// <param name="ip"></param> private void ReMoveSocketClient(string ip) { lockSlim.EnterWriteLock(); try { if (dictsocket.ContainsKey(ip)) { string id = dictsocket[ip].id; dictsocket.Remove(ip); OnClientClose?.Invoke(this, new SocketArgs(new ClientInfo() { ip = ip.Trim(), id = id.Trim() })); } } catch (Exception ex) { OnError?.Invoke($"Error when removing a client:{ex.ToString()}"); } finally { lockSlim.ExitWriteLock(); } }
private void ReceiveCallBack(IAsyncResult asyncResult) { //Socket socket = (Socket)asyncResult.AsyncState; TCPConnection client = (TCPConnection)asyncResult.AsyncState; if (!client.Socket.Connected) { return; } int receiveBytes = 0; try { receiveBytes = client.Socket.EndReceive(asyncResult); } catch (SocketException sex) { if (sex.SocketErrorCode == SocketError.ConnectionReset) { OnClientClose?.Invoke(client.Socket.RemoteEndPoint); ClientSockets.Remove(client.Socket.RemoteEndPoint); } else { OnException?.Invoke(sex); } } catch (Exception ex) { OnException?.Invoke(ex); return; } if (receiveBytes == 0) { return; } byte[] receiveBuffer = new byte[receiveBytes]; Array.Copy(client.ReceiveBuffer, receiveBuffer, receiveBytes); string receiveData = Encoding.ASCII.GetString(receiveBuffer); try { OnReceive?.Invoke(client.Socket.RemoteEndPoint, receiveData); } catch (Exception ex) { OnException?.Invoke(ex); } }
public WSServer(int port) { context = SynchronizationContext.Current; wss = new WebSocketServer(port); wss.AddWebSocketService <WSBehaviour>("/", behaviour => { behaviour.OnClientConnect += (id, ws) => { context.Post(_ => { OnClientConnect.Invoke(id, ws); }, null); }; behaviour.OnClientData += (ws, e) => { context.Post(_ => { if (e.IsText) { OnTextData.Invoke(ws, e.Data); } else if (e.IsBinary) { OnBinaryData.Invoke(ws, e.RawData); } }, null); }; behaviour.OnClientClose += (ws, e) => { context.Post(_ => { OnClientClose.Invoke(ws); }, null); }; behaviour.OnClientError += (id, e) => { context.Post(_ => { OnClientError.Invoke(id, e.Exception); }, null); }; }); }
private void _OnClose(object sender, DataEventArgs <string, WebSocketClient> e) { OnClientClose?.Invoke(this, e); WebSocketClientMg.Instance.Remove(e.Arg1); }