//处理客户端连接的函数 private void HandleTcpClientAccepted(IAsyncResult ar) { if (IsRunning) { var _Client = m_Listener.EndAcceptTcpClient(ar); if (m_ClientCount > NetworkDefine.MaxConnect) { //TODO _Client.Close(); return; } var _Session = new TCPClientSession(_Client, m_ClientID++); lock (m_Clients) { m_ClientCount++; m_Clients.Add(_Session.ClientID, _Session); OnClientConnected(_Session); } var _Stream = _Session.NetworkStream; //开始异步读取数据 _Stream.BeginRead(_Session.Buffer, 0, _Session.Buffer.Length, HandleDataReceived, _Session); m_Listener.BeginAcceptTcpClient(HandleTcpClientAccepted, ar.AsyncState); } }
//关闭一个与客户端之间的会话 public void Close(TCPClientSession pSession, bool pRemove = true) { if (pSession != null) { pSession.Close(); if (pRemove) { m_Clients.Remove(pSession.ClientID); } OnClientClosed(pSession); } }
private void OnClientClosed(TCPClientSession session) { m_ClientCount--; ClientClosed?.Invoke(this, session); }
private void OnDataReceived(TCPClientSession session) { DataReceived?.Invoke(this, session); }
private void OnClientDisconnected(TCPClientSession session) { m_ClientCount--; session.EventMsg = "连接断开"; ClientDisconnected?.Invoke(this, session); }
private void OnClientConnected(TCPClientSession session) { ClientConnected?.Invoke(this, session); }
public void Send(TCPClientSession session, byte[] data, int pLen) { Send(session.TcpClient, data, pLen); }
//发送数据 public void Send(TCPClientSession session, byte[] data) { Send(session.TcpClient, data, data.Length); }