/// <summary> /// 接收数据事件 /// </summary> /// <param name="ar"></param> private void OnRecvClientData(IAsyncResult ar) { TCPClientState state = (TCPClientState)ar.AsyncState; try { if (!m_bRun) { return; } byte[] buf = state.ReadData(ar); if (buf == null) { // connection has been closed lock (m_ClientList) { m_ClientList.Remove(state); } state.Close(); return; } if (state.ClientType == CLIENTTYPE.CLIENT) { if (!OnClientData(state, buf)) { state.Close(); return; } } else if (state.ClientType == CLIENTTYPE.CONTROLLER) { if (!OnControllerData(state, buf)) { state.Close(); return; } } else { state.Close(); return; } // continue listening for tcp datagram packets state.NetworkStream.BeginRead(state.Buffer, 0, state.Buffer.Length, OnRecvClientData, state); } catch (Exception e) { Logger.Trace(e); state.Close(); } }
/// <summary> /// 关闭 /// </summary> public void Close() { //关闭数据的接受和发送 try { if (this.TcpClient == null) { return; } if (ClientType == CLIENTTYPE.CLIENT) { Logger.Trace("Client Close code=" + conncode); if (conncode != null && conncode != "") { ConnCode.DelState(conncode); } } else if (ClientType == CLIENTTYPE.CONTROLLER) { Logger.Trace("Controller Close code=" + conncode); } TcpClient myclient = this.TcpClient; TCPClientState peer = this.PeerTcpClient; this.TcpClient = null; this.PeerTcpClient = null; if (peer != null) { peer.PeerTcpClient = null; peer.Close(); } if (myclient != null) { if (myclient.Connected) { myclient.Close(); } } } catch (Exception e) { Logger.Trace(e); } Buffer = null; }