Esempio n. 1
0
        /// <summary>
        /// 此方法在异步接收操作完成时调用。
        /// </summary>
        /// <param name="e"></param>
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            AsyncUserToken userToken = e.UserToken as AsyncUserToken;

            if (userToken.Socket == null)
            {
                return;
            }

            userToken.ActiveDateTime = DateTime.Now;
            //检查远程主机是否关闭了连接
            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                int    offset = e.Offset;
                int    count  = e.BytesTransferred;
                byte[] data   = new byte[count];
                for (int i = offset; i < count; i++)
                {
                    data[i] = e.Buffer[i];
                }

                //触发接收数据事件
                ClientReceiveData?.Invoke(userToken, data);
                //继续异步接收
                bool willRaiseEvent = userToken.Socket.ReceiveAsync(userToken.RecvEventArgs);
                if (!willRaiseEvent)
                {
                    ProcessReceive(userToken.RecvEventArgs);
                }
            }
            else
            {
                userToken.AsyncClose();
            }
        }
Esempio n. 2
0
        /// <summary>
        /// 异步发送回调函数
        /// </summary>
        /// <param name="asyncEventArgs"></param>
        private ResMsg ProcessSend(SocketAsyncEventArgs sendEventArgs)
        {
            AsyncUserToken userToken = sendEventArgs.UserToken as AsyncUserToken;

            userToken.ActiveDateTime = DateTime.Now;
            if (sendEventArgs.SocketError == SocketError.Success)
            {
                //发送成功,检查缓存中是否还有数据没有发送,有就继续发送
                byte[] data;
                if (userToken.SendBuffer.TryDequeue(out data) && data != null)
                {
                    userToken.m_sendAsync = true;
                    return(SendAsyncEvent(userToken, data, 0, data.Length));
                }
                userToken.m_sendAsync = false;
                return(new ResMsg(true, ""));
            }
            else
            {
                userToken.AsyncClose();
                return(new ResMsg(false, "连接已关闭"));
            }
        }