public AsyncEventArgs(TCPClientState state) { this._state = state; IsHandled = false; }
public AsyncEventArgs(string msg, TCPClientState state) { this._msg = msg; this._state = state; IsHandled = false; }
private void RaiseOtherException(TCPClientState state) { RaiseOtherException(state, ""); }
/// <summary> /// 关闭一个与客户端之间的会话 /// </summary> /// <param name="state">需要关闭的客户端会话对象</param> public void Close(TCPClientState state) { if (state != null) { state.Close(); _clients.Remove(state); _clientCount--; //TODO 触发关闭事件 } }
/// <summary> /// 触发网络错误事件 /// </summary> /// <param name="state"></param> private void RaiseNetError(TCPClientState state) { if (NetError != null) { NetError(this, new AsyncEventArgs(state)); } }
/// <summary> /// 触发异常事件 /// </summary> /// <param name="state"></param> private void RaiseOtherException(TCPClientState state, string descrip) { if (OtherException != null) { OtherException(this, new AsyncEventArgs(descrip, state)); } }
/// <summary> /// 触发发送数据前的事件 /// </summary> /// <param name="state"></param> private void RaisePrepareSend(TCPClientState state) { if (PrepareSend != null) { PrepareSend(this, new AsyncEventArgs(state)); } }
private void RaiseDataReceived(TCPClientState state,byte[] buffer) { if (DataReceived != null) { DataReceived(state, buffer); } }
/// <summary> /// 触发客户端连接断开事件 /// </summary> /// <param name="client"></param> private void RaiseClientDisconnected(TCPClientState state) { if (ClientDisconnected != null) { ClientDisconnected(this, new AsyncEventArgs(state)); } }
/// <summary> /// 发送数据 /// </summary> /// <param name="state">接收数据的客户端会话</param> /// <param name="data">数据报文</param> public void Send(TCPClientState state, byte[] data) { RaisePrepareSend(state); Send(state.TcpClient, data); }
/// <summary> /// 处理客户端连接的函数 /// </summary> /// <param name="ar"></param> private void HandleTcpClientAccepted(IAsyncResult ar) { if (IsRunning) { try { //TcpListener tcpListener = (TcpListener)ar.AsyncState; //Log.LogHelper.WriteInfo("enter HandleTcpClientAccepted"); //Log.LogHelper.WriteInfo(ar.); TcpClient client = _listener.EndAcceptTcpClient(ar); byte[] buffer = new byte[client.ReceiveBufferSize]; TCPClientState state = new TCPClientState(client, buffer); lock (_clients) { _clients.Add(state); RaiseClientConnected(state); //Log.LogHelper.WriteInfo("RaiseClientConnected complete"); } NetworkStream stream = state.NetworkStream; //开始异步读取数据 //Log.LogHelper.WriteInfo("BeginRead start"); stream.BeginRead(state.Buffer, 0, state.Buffer.Length, HandleDataReceived, state); //Log.LogHelper.WriteInfo("BeginRead complete"); } catch (Exception ex) { Log.LogHelper.WriteError(ex.Message + ex.StackTrace); } finally { _listener.BeginAcceptTcpClient( new AsyncCallback(HandleTcpClientAccepted), ar.AsyncState); } } }