Beispiel #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();
            }
        }
Beispiel #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);
                }
            }
        }
Beispiel #3
0
 public AsyncSocketEventArgs(string msg, AsyncSocketState state)
 {
     this._msg   = msg;
     this._state = state;
     IsHandled   = false;
 }
Beispiel #4
0
 public AsyncSocketEventArgs(AsyncSocketState state)
 {
     this._state = state;
     IsHandled   = false;
 }
Beispiel #5
0
 private void RaiseOtherException(AsyncSocketState state)
 {
     RaiseOtherException(state, "");
 }
Beispiel #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);
 }