Exemple #1
0
        /// <summary>
        /// 关闭一个与客户端之间的会话
        /// </summary>
        /// <param name="state">须要关闭的客户端会话对象</param>
        public void Close(AsyncSocketState state)
        {
            if (state != null)
            {
                state.Datagram       = null;
                state.RecvDataBuffer = null;

                _clients.Remove(state);
                _clientCount--;
                //TODO 触发关闭事件
                state.Close();
            }
        }
Exemple #2
0
        /// <summary>
        /// 处理客户端数据
        /// </summary>
        /// <param name="ar"></param>
        private void HandleDataReceived(IAsyncResult ar)
        {
            if (IsRunning)
            {
                AsyncSocketState state  = (AsyncSocketState)ar.AsyncState;
                Socket           client = state.ClientSocket;
                try
                {
                    //假设两次開始了异步的接收,所以当客户端退出的时候
                    //会两次执行EndReceive
                    int recv = client.EndReceive(ar);
                    if (recv == 0)
                    {
                        //C- TODO 触发事件 (关闭客户端)
                        Close(state);
                        RaiseNetError(state);
                        return;
                    }
                    //TODO 处理已经读取的数据 ps:数据在state的RecvDataBuffer中

                    //C- TODO 触发数据接收事件
                    RaiseDataReceived(state);
                }
                catch (SocketException)
                {
                    //C- TODO 异常处理
                    RaiseNetError(state);
                }
                finally
                {
                    //继续接收来自来客户端的数据
                    client.BeginReceive(state.RecvDataBuffer, 0, state.RecvDataBuffer.Length, SocketFlags.None,
                                        new AsyncCallback(HandleDataReceived), state);
                }
            }
        }
Exemple #3
0
 public AsyncSocketEventArgs(byte[] msg, AsyncSocketState state)
 {
     this._msg   = msg;
     this._state = state;
     IsHandled   = false;
 }
Exemple #4
0
 public AsyncSocketEventArgs(AsyncSocketState state)
 {
     this._msg   = state.RecvDataBuffer;
     this._state = state;
     IsHandled   = false;
 }
Exemple #5
0
 private void RaiseOtherException(AsyncSocketState state)
 {
     RaiseOtherException(state, new byte[] {});
 }
Exemple #6
0
 /// <summary>
 /// 发送数据
 /// </summary>
 /// <param name="state">接收数据的客户端会话</param>
 /// <param name="data">数据报文</param>
 public void Send(AsyncSocketState state, byte[] data)
 {
     RaisePrepareSend(state);
     Send(state.ClientSocket, data);
 }