/// <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 RaiseCompletedSend(TcpClientState state) { if (CompletedSend != null) { CompletedSend(this, new AsyncEventArgs(state)); } }
/// <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 RaisePrepareSend(TcpClientState state) { if (PrepareSend != null) { PrepareSend(this, new AsyncEventArgs(state)); } }
private void RaiseDataReceived(TcpClientState state) { if (DataReceived != null) { DataReceived(this, new AsyncEventArgs(state)); } }
/// <summary> /// 触发客户端连接断开事件 /// </summary> /// <param name="client"></param> private void RaiseClientDisconnected(TcpClientState state) { if (ClientDisconnected != null) { ClientDisconnected(this, new AsyncEventArgs("连接断开")); } }
/// <summary> /// 关闭一个与客户端之间的会话 /// </summary> /// <param name="state">需要关闭的客户端会话对象</param> public void Close(TcpClientState state) { if (state != null) { clients.Remove(state); clientCount--; //TODO 触发关闭事件 } }
/// <summary> /// 处理客户端连接的函数 /// </summary> /// <param name="ar"></param> private void HandleTcpClientAccepted(IAsyncResult ar) { if (IsRunning) { var client = listener.EndAcceptTcpClient(ar); byte[] buffer = new byte[client.ReceiveBufferSize]; var state = new TcpClientState(client, buffer); lock (clients) { clients.Add(state); RaiseClientConnected(state); } var stream = state.NetworkStream; //开始异步读取数据 stream.BeginRead(state.Buffer, 0, state.Buffer.Length, HandleDataReceived, state); listener.BeginAcceptTcpClient( new AsyncCallback(HandleTcpClientAccepted), ar.AsyncState); } }
public AsyncEventArgs(string msg, TcpClientState state) { this.msg = msg; this.state = state; IsHandled = false; }
public AsyncEventArgs(TcpClientState state) { this.state = state; IsHandled = false; }
private void RaiseOtherException(TcpClientState state) { RaiseOtherException(state, ""); }
/// <summary> /// 发送数据 /// </summary> /// <param name="state">接收数据的客户端会话</param> /// <param name="data">数据报文</param> public void Send(TcpClientState state, byte[] data) { RaisePrepareSend(state); Send(state.TcpClient, data); }