Ejemplo n.º 1
0
        public int HandlePrefix(SocketAsyncEventArgs saea, DataToken dataToken, int remainingBytesToProcess)
        {
            if (remainingBytesToProcess >= 4 - dataToken.prefixBytesDone)
            {
                for (int i = 0; i < 4 - dataToken.prefixBytesDone; i++)
                {
                    dataToken.byteArrayForPrefix[dataToken.prefixBytesDone + i] = saea.Buffer[dataToken.DataOffset + i];
                }
                remainingBytesToProcess = remainingBytesToProcess - 4 + dataToken.prefixBytesDone;
                dataToken.bufferSkip += 4 - dataToken.prefixBytesDone;
                dataToken.prefixBytesDone = 4;
                dataToken.messageLength = BitConverter.ToInt32(dataToken.byteArrayForPrefix, 0);
            }
            else
            {
                for (int i = 0; i < remainingBytesToProcess; i++)
                {
                    dataToken.byteArrayForPrefix[dataToken.prefixBytesDone + i] = saea.Buffer[dataToken.DataOffset + i];
                }
                dataToken.prefixBytesDone += remainingBytesToProcess;
                remainingBytesToProcess = 0;
            }

            return remainingBytesToProcess;
        }
Ejemplo n.º 2
0
        private void ProcessSend(SocketAsyncEventArgs ioEventArgs)
        {
            DataToken dataToken = (DataToken)ioEventArgs.UserToken;

            if (ioEventArgs.SocketError == SocketError.Success)
            {
                dataToken.messageBytesDone += ioEventArgs.BytesTransferred;
                if (dataToken.messageBytesDone != dataToken.messageLength)
                {
                    PostSend(ioEventArgs);
                }
                else
                {
                    dataToken.Reset(true);
                    try
                    {
                        TryDequeueAndPostSend(dataToken.Socket, ioEventArgs);
                    }
                    catch
                    {
                        dataToken.Socket.ResetSendFlag();
                        throw;
                    }
                }
            }
            else
            {
                dataToken.Socket.ResetSendFlag();
                HandleCloseSocket(ioEventArgs);
            }
        }
Ejemplo n.º 3
0
        private void TryDequeueAndPostSend(ExSocket socket, SocketAsyncEventArgs ioEventArgs)
        {
            bool isOwner = ioEventArgs == null;

            byte[] data;
            if (socket.TryDequeue(out data))
            {
                if (ioEventArgs == null)
                {
                    ioEventArgs = ioEventArgsPool.Pop();
                    ioEventArgs.AcceptSocket = socket.WorkSocket;
                }
                DataToken dataToken = (DataToken)ioEventArgs.UserToken;
                dataToken.Socket = socket;
                dataToken.byteArrayForMessage = data;
                dataToken.messageLength       = data.Length;
                try
                {
                    PostSend(ioEventArgs);
                }
                catch
                {
                    if (isOwner)
                    {
                        ReleaseIOEventArgs(ioEventArgs);
                    }
                    throw;
                }
            }
            else
            {
                ReleaseIOEventArgs(ioEventArgs);
                socket.ResetSendFlag();
            }
        }
Ejemplo n.º 4
0
        private void IO_Completed(object sender, SocketAsyncEventArgs ioEventArgs)
        {
            try
            {
                DataToken ioDataToken = (DataToken)ioEventArgs.UserToken;
                ioDataToken.Socket.LastAccessTime = DateTime.Now;
                switch (ioEventArgs.LastOperation)
                {
                case SocketAsyncOperation.Receive:
                    ProcessReceive(ioEventArgs);
                    break;

                case SocketAsyncOperation.Send:
                    ProcessSend(ioEventArgs);
                    break;

                default:
                    throw new ArgumentException("The last operation completed on the socket was not a receive or send");
                }
            }
            catch (ObjectDisposedException)
            {
                ReleaseIOEventArgs(ioEventArgs);
            }
            catch (Exception ex)
            {
                logger.Error("IO_Completed", ex);
            }
        }
Ejemplo n.º 5
0
        public int HandleMessage(SocketAsyncEventArgs saea, DataToken dataToken, int remainingBytesToProcess)
        {
            if (dataToken.messageBytesDone == 0)
            {
                dataToken.byteArrayForMessage = new byte[dataToken.messageLength];
            }

            var nonCopiedBytes = 0;

            if (remainingBytesToProcess + dataToken.messageBytesDone >= dataToken.messageLength)
            {
                var copyedBytes = dataToken.RemainByte;
                nonCopiedBytes = remainingBytesToProcess - copyedBytes;
                Buffer.BlockCopy(saea.Buffer, dataToken.DataOffset, dataToken.byteArrayForMessage, dataToken.messageBytesDone, copyedBytes);
                dataToken.messageBytesDone = dataToken.messageLength;
                dataToken.bufferSkip      += copyedBytes;
            }
            else
            {
                Buffer.BlockCopy(saea.Buffer, dataToken.DataOffset, dataToken.byteArrayForMessage, dataToken.messageBytesDone, remainingBytesToProcess);
                dataToken.messageBytesDone += remainingBytesToProcess;
            }

            return(nonCopiedBytes);
        }
Ejemplo n.º 6
0
        public int HandlePrefix(SocketAsyncEventArgs saea, DataToken dataToken, int remainingBytesToProcess)
        {
            if (remainingBytesToProcess >= 4 - dataToken.prefixBytesDone)
            {
                for (int i = 0; i < 4 - dataToken.prefixBytesDone; i++)
                {
                    dataToken.byteArrayForPrefix[dataToken.prefixBytesDone + i] = saea.Buffer[dataToken.DataOffset + i];
                }
                remainingBytesToProcess   = remainingBytesToProcess - 4 + dataToken.prefixBytesDone;
                dataToken.bufferSkip     += 4 - dataToken.prefixBytesDone;
                dataToken.prefixBytesDone = 4;
                dataToken.messageLength   = BitConverter.ToInt32(dataToken.byteArrayForPrefix, 0);
            }
            else
            {
                for (int i = 0; i < remainingBytesToProcess; i++)
                {
                    dataToken.byteArrayForPrefix[dataToken.prefixBytesDone + i] = saea.Buffer[dataToken.DataOffset + i];
                }
                dataToken.prefixBytesDone += remainingBytesToProcess;
                remainingBytesToProcess    = 0;
            }

            return(remainingBytesToProcess);
        }
Ejemplo n.º 7
0
        public void Connect()
        {
            socket = new Socket(this.clientSettings.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(this.clientSettings.RemoteEndPoint);
            connected = true;

            var buffer = new byte[this.clientSettings.BufferSize * 2];

            this.sendEventArg = new SocketAsyncEventArgs();
            this.sendEventArg.SetBuffer(buffer, 0, this.clientSettings.BufferSize);
            this.sendDataToken = new DataToken();
            this.sendDataToken.bufferOffset = this.sendEventArg.Offset;
            this.sendEventArg.UserToken     = this.sendDataToken;
            this.sendEventArg.AcceptSocket  = socket;
            this.sendEventArg.Completed    += new EventHandler <SocketAsyncEventArgs>(IO_Completed);

            this.receiveEventArg = new SocketAsyncEventArgs();
            this.receiveEventArg.SetBuffer(buffer, this.clientSettings.BufferSize, this.clientSettings.BufferSize);
            this.receiveDataToken = new DataToken();
            this.receiveDataToken.bufferOffset = this.receiveEventArg.Offset;
            this.receiveEventArg.UserToken     = this.receiveDataToken;
            this.receiveEventArg.AcceptSocket  = socket;
            this.receiveEventArg.Completed    += new EventHandler <SocketAsyncEventArgs>(IO_Completed);

            PostReceive();
        }
Ejemplo n.º 8
0
        private void IO_Completed(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                DataToken ioDataToken = (DataToken)e.UserToken;

                switch (e.LastOperation)
                {
                case SocketAsyncOperation.Receive:
                    ProcessReceive();
                    break;

                case SocketAsyncOperation.Send:
                    ProcessSend();
                    break;

                default:
                    throw new ArgumentException("The last operation completed on the socket was not a receive or send");
                }
            }
            catch (ObjectDisposedException) { }
            catch (Exception ex)
            {
                logger.Error("IO_Completed", ex);
            }
        }
Ejemplo n.º 9
0
 private void TryDequeueAndPostSend()
 {
     byte[] data;
     if (sendQueue.TryDequeue(out data))
     {
         DataToken dataToken = sendDataToken;
         dataToken.byteArrayForMessage = data;
         dataToken.messageLength       = data.Length;
         PostSend();
     }
     else
     {
         ResetSendFlag();
     }
 }
Ejemplo n.º 10
0
        private void PostSend(SocketAsyncEventArgs ioEventArgs)
        {
            DataToken dataToken = (DataToken)ioEventArgs.UserToken;

            if (dataToken.messageLength - dataToken.messageBytesDone <= this.socketSettings.BufferSize)
            {
                ioEventArgs.SetBuffer(dataToken.bufferOffset, dataToken.messageLength - dataToken.messageBytesDone);
                Buffer.BlockCopy(dataToken.byteArrayForMessage, dataToken.messageBytesDone, ioEventArgs.Buffer, dataToken.bufferOffset, dataToken.messageLength - dataToken.messageBytesDone);
            }
            else
            {
                ioEventArgs.SetBuffer(dataToken.bufferOffset, this.socketSettings.BufferSize);
                Buffer.BlockCopy(dataToken.byteArrayForMessage, dataToken.messageBytesDone, ioEventArgs.Buffer, dataToken.bufferOffset, this.socketSettings.BufferSize);
            }

            var willRaiseEvent = ioEventArgs.AcceptSocket.SendAsync(ioEventArgs);

            if (!willRaiseEvent)
            {
                ProcessSend(ioEventArgs);
            }
        }
Ejemplo n.º 11
0
        private void Init()
        {
            this.bufferManager.InitBuffer();

            for (int i = 0; i < this.socketSettings.MaxAcceptOps; i++)
            {
                this.acceptEventArgsPool.Push(CreateAcceptEventArgs());
            }

            SocketAsyncEventArgs ioEventArgs;

            for (int i = 0; i < this.socketSettings.NumOfSaeaForRecSend; i++)
            {
                ioEventArgs = new SocketAsyncEventArgs();
                this.bufferManager.SetBuffer(ioEventArgs);
                ioEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                DataToken dataToken = new DataToken();
                dataToken.bufferOffset = ioEventArgs.Offset;
                ioEventArgs.UserToken  = dataToken;
                this.ioEventArgsPool.Push(ioEventArgs);
            }
        }
Ejemplo n.º 12
0
        public int HandleMessage(SocketAsyncEventArgs saea, DataToken dataToken, int remainingBytesToProcess)
        {
            if (dataToken.messageBytesDone == 0)
            {
                dataToken.byteArrayForMessage = new byte[dataToken.messageLength];
            }

            var nonCopiedBytes = 0;
            if (remainingBytesToProcess + dataToken.messageBytesDone >= dataToken.messageLength)
            {
                var copyedBytes = dataToken.RemainByte;
                nonCopiedBytes = remainingBytesToProcess - copyedBytes;
                Buffer.BlockCopy(saea.Buffer, dataToken.DataOffset, dataToken.byteArrayForMessage, dataToken.messageBytesDone, copyedBytes);
                dataToken.messageBytesDone = dataToken.messageLength;
                dataToken.bufferSkip += copyedBytes;
            }
            else
            {
                Buffer.BlockCopy(saea.Buffer, dataToken.DataOffset, dataToken.byteArrayForMessage, dataToken.messageBytesDone, remainingBytesToProcess);
                dataToken.messageBytesDone += remainingBytesToProcess;
            }

            return nonCopiedBytes;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 处理数据接收回调
        /// </summary>
        /// <param name="ioEventArgs"></param>
        private void ProcessReceive(SocketAsyncEventArgs ioEventArgs)
        {
            DataToken dataToken = (DataToken)ioEventArgs.UserToken;

            if (ioEventArgs.SocketError != SocketError.Success)
            {
                //Socket错误
                if (logger.IsDebugEnabled)
                {
                    logger.Debug("ProcessReceive:{0}", ioEventArgs.SocketError);
                }
                HandleCloseSocket(ioEventArgs);
                return;
            }

            if (ioEventArgs.BytesTransferred == 0)
            {
                //对方主动关闭socket
                if (logger.IsDebugEnabled)
                {
                    logger.Debug("对方关闭Socket");
                }
                HandleCloseSocket(ioEventArgs);
                return;
            }

            var exSocket = dataToken.Socket;

            #region 数据解析
            List <byte[]> msgs = new List <byte[]>();
            int           remainingBytesToProcess = ioEventArgs.BytesTransferred;
            bool          needPostAnother         = true;
            do
            {
                if (dataToken.prefixBytesDone < 4)
                {
                    remainingBytesToProcess = prefixHandler.HandlePrefix(ioEventArgs, dataToken, remainingBytesToProcess);
                    if (dataToken.prefixBytesDone == 4 && (dataToken.messageLength > 10 * 1024 * 1024 || dataToken.messageLength <= 0))
                    {
                        //消息头已接收完毕,并且接收到的消息长度大于10M,socket传输的数据已紊乱,关闭掉
                        logger.Warn("接收到的消息长度错误:{0}", dataToken.messageLength);
                        needPostAnother = false;
                        HandleCloseSocket(ioEventArgs);
                        break;
                    }
                    if (logger.IsDebugEnabled)
                    {
                        logger.Debug("处理消息头,消息长度[{0}],剩余字节[{1}]", dataToken.messageLength, remainingBytesToProcess);
                    }
                    if (remainingBytesToProcess == 0)
                    {
                        break;
                    }
                }

                remainingBytesToProcess = messageHandler.HandleMessage(ioEventArgs, dataToken, remainingBytesToProcess);

                if (dataToken.IsMessageReady)
                {
                    if (logger.IsDebugEnabled)
                    {
                        logger.Debug("完整封包 长度[{0}],总传输[{1}],剩余[{2}]", dataToken.messageLength, ioEventArgs.BytesTransferred, remainingBytesToProcess);
                    }
                    msgs.Add(dataToken.byteArrayForMessage);
                    if (remainingBytesToProcess != 0)
                    {
                        if (logger.IsDebugEnabled)
                        {
                            logger.Debug("重置缓冲区,buffskip指针[{0}]。", dataToken.bufferSkip);
                        }
                        dataToken.Reset(false);
                    }
                }
                else
                {
                    if (logger.IsDebugEnabled)
                    {
                        logger.Debug("不完整封包 长度[{0}],总传输[{1}],已接收[{2}]", dataToken.messageLength, ioEventArgs.BytesTransferred, dataToken.messageBytesDone);
                    }
                }
            } while (remainingBytesToProcess != 0);
            #endregion

            if (needPostAnother)
            {
                if (dataToken.prefixBytesDone == 4 && dataToken.IsMessageReady)
                {
                    dataToken.Reset(true);
                }
                dataToken.bufferSkip = 0;
                PostReceive(ioEventArgs);
            }

            foreach (var m in msgs)
            {
                try
                {
                    OnDataReceived(new ConnectionEventArgs {
                        Socket = exSocket, Data = m
                    });
                }
                catch (Exception ex)
                {
                    logger.Error("OnDataReceived", ex);
                }
            }
        }
Ejemplo n.º 14
0
        private void Init()
        {
            this.bufferManager.InitBuffer();

            for (int i = 0; i < this.socketSettings.MaxAcceptOps; i++)
            {
                this.acceptEventArgsPool.Push(CreateAcceptEventArgs());
            }

            SocketAsyncEventArgs ioEventArgs;
            for (int i = 0; i < this.socketSettings.NumOfSaeaForRecSend; i++)
            {
                ioEventArgs = new SocketAsyncEventArgs();
                this.bufferManager.SetBuffer(ioEventArgs);
                ioEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
                DataToken dataToken = new DataToken();
                dataToken.bufferOffset = ioEventArgs.Offset;
                ioEventArgs.UserToken = dataToken;
                this.ioEventArgsPool.Push(ioEventArgs);
            }
        }
Ejemplo n.º 15
0
        public void Connect()
        {
            socket = new Socket(this.clientSettings.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(this.clientSettings.RemoteEndPoint);
            connected = true;

            var buffer = new byte[this.clientSettings.BufferSize * 2];
            this.sendEventArg = new SocketAsyncEventArgs();
            this.sendEventArg.SetBuffer(buffer, 0, this.clientSettings.BufferSize);
            this.sendDataToken = new DataToken();
            this.sendDataToken.bufferOffset = this.sendEventArg.Offset;
            this.sendEventArg.UserToken = this.sendDataToken;
            this.sendEventArg.AcceptSocket = socket;
            this.sendEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);

            this.receiveEventArg = new SocketAsyncEventArgs();
            this.receiveEventArg.SetBuffer(buffer, this.clientSettings.BufferSize, this.clientSettings.BufferSize);
            this.receiveDataToken = new DataToken();
            this.receiveDataToken.bufferOffset = this.receiveEventArg.Offset;
            this.receiveEventArg.UserToken = this.receiveDataToken;
            this.receiveEventArg.AcceptSocket = socket;
            this.receiveEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);

            PostReceive();
        }