private void StartListen() { try { _socket.BeginAccept(asyncResult => { try { Socket newSocket = _socket.EndAccept(asyncResult); //马上进行下一轮监听,增加吞吐量 if (_isListen) { StartListen(); } TcpSocketConnection newConnection = new TcpSocketConnection(newSocket, this, RecLength) { HandleRecMsg = HandleRecMsg == null ? null : new Action <TcpSocketServer, TcpSocketConnection, byte[]>(HandleRecMsg), HandleClientClose = HandleClientClose == null ? null : new Action <TcpSocketServer, TcpSocketConnection>(HandleClientClose), HandleSendMsg = HandleSendMsg == null ? null : new Action <TcpSocketServer, TcpSocketConnection, byte[]>(HandleSendMsg), HandleException = HandleException == null ? null : new Action <Exception>(HandleException) }; AddConnection(newConnection); newConnection.StartRecMsg(); HandleNewClientConnected?.Invoke(this, newConnection); } catch (Exception ex) { HandleException?.Invoke(ex); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } }
/// <summary> /// 构造函数 /// </summary> /// <param name="webSocketServer">WebSocket端</param> /// <param name="con">TcpSocketConnection连接对象</param> public WebSocketConnection(WebSocketServer webSocketServer, TcpSocketConnection con) { _webSocketServer = webSocketServer; _theCon = con; }
/// <summary> /// 添加客户端连接 /// </summary> /// <param name="theConnection">需要添加的客户端连接</param> private void AddConnection(TcpSocketConnection theConnection) { _connectionList[theConnection.ConnectionId] = theConnection; }
/// <summary> /// 关闭指定客户端连接 /// </summary> /// <param name="theConnection">指定的客户端连接</param> public void CloseConnection(TcpSocketConnection theConnection) { theConnection.Close(); }