示例#1
0
        private void CloseClientSocket(SocketAsyncEventArgs e)
        {
            AsyncUserToken token = e.UserToken as AsyncUserToken;

            try
            {
                token.UserSocket.Shutdown(SocketShutdown.Send);
            }
            catch (Exception) { }
            dicSAEA.Remove(token.UserSocket.RemoteEndPoint.ToString());
            token.UserSocket.Close();

            maxClient.Release();
            rwPool.Push(e);
        }
示例#2
0
        /// <summary>
        /// 接收消息回调处理
        /// </summary>
        /// <param name="e"></param>
        public void OnReceiveCompleted(SocketAsyncEventArgs e)
        {
            if (e.SocketError != SocketError.Success)
            {
                return;                                         //判断消息的接收状态
            }
            AsyncUserToken token        = e.UserToken as AsyncUserToken;
            int            lengthBuffer = e.BytesTransferred; //获取接收的字节长度
            string         ipAddress    = token.UserSocket.RemoteEndPoint.ToString();
            MessageFormat  msg          = new MessageFormat();

            //如果接收的字节长度为0,则判断远端服务器关闭连接
            if (lengthBuffer <= 0)
            {
                msg.msgStr = "远端服务器已经断开连接";
                msg.ipStr  = ipAddress;
                if (OnDisconnectEvent != null)
                {
                    OnDisconnectEvent(msg);
                }
                CloseClientSocket(e);
            }
            else
            {
                byte[] receiveBuffer = e.Buffer;
                byte[] buffer        = new byte[lengthBuffer];
                Buffer.BlockCopy(receiveBuffer, 0, buffer, 0, lengthBuffer);
                msg.msgStr = Encoding.Unicode.GetString(buffer);
                msg.ipStr  = ipAddress;
                bool willRaiseEvent = token.UserSocket.ReceiveAsync(e);     //继续异步接收消息
                if (!willRaiseEvent)
                {
                    OnReceiveCompleted(e);
                }
                if (OnReceiveCompletedEvent != null)
                {
                    OnReceiveCompletedEvent(msg);                                         //调用UI方法处理
                }
            }
        }