示例#1
0
        /// <summary>
        /// 这个方法在异步接收操作完成时调用.
        /// 如果远程主机关闭连接Socket将关闭
        /// </summary>
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            AsyncUserToken token = (AsyncUserToken)e.UserToken;

            // 检查远程主机是否关闭连接

            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                // 增加接收到的字节总数
                Interlocked.Add(ref m_totalBytesRead, e.BytesTransferred);
                Debug.WriteLine(string.Format("服务器读取字节总数:{0}", m_totalBytesRead));

                //byte[] destinationArray = new byte[e.BytesTransferred];// 目的字节数组
                //Array.Copy(e.Buffer, 0, destinationArray, 0, e.BytesTransferred);
                token.SetBytesReceived(e.BytesTransferred);

                EventHandler <AsyncUserToken> handler = OnClientRead;

                // 如果订户事件将为空(null)
                if (handler != null)
                {
                    handler(this, token);// 抛出接收到数据事件
                }

                try
                {
                    // 继续接收数据
                    bool willRaiseEvent = token.Socket.ReceiveAsync(e);
                    if (!willRaiseEvent)
                    {
                        ProcessReceive(e);
                    }
                }
                catch (ObjectDisposedException)
                {
                    RaiseDisconnectedEvent(token);
                }
                catch (SocketException socketException)
                {
                    if (socketException.ErrorCode == (int)SocketError.ConnectionReset) //10054一个建立的连接被远程主机强行关闭
                    {
                        RaiseDisconnectedEvent(token);                                 //引发断开连接事件
                    }
                    else
                    {
                        RaiseErrorEvent(token, new AsyncSocketException("在SocketAsyncEventArgs对象上执行异步接收数据操作时发生SocketException异常", socketException));
                    }
                }
                catch (Exception exception_debug)
                {
                    Debug.WriteLine("调试:" + exception_debug.Message);
                    throw exception_debug;
                }
            }
            else
            {
                RaiseDisconnectedEvent(token);
            }
        }