Esempio n. 1
0
        protected override void ChannelRead0(IChannelHandlerContext context, IByteBuffer message)
        {
            int msgType = message.GetInt(4);
            int svrID   = msgType / 10000;
            int msgLen  = message.GetInt(0);
            var msgData = message.GetIoBuffer(8, msgLen - 8);

            Log.Info("msg : {0}", msgType);

            IGateMessage gate = null;

            if (svrID == 1)
            {
                gate = clusterClient.GetGrain <IGateMaster>(0);
            }

            if (svrID == 3)
            {
                gate = clusterClient.GetGrain <IGateBattle>(0);
            }

            if (gate != null)
            {
                Task.Run(async() =>
                {
                    var response = await gate.SendMessage(msgType, msgData.ToArray());
                    if (response != null)
                    {
                        //约定response msg id = req + 1
                        await Send(msgType + 1, response);
                    }
                });
            }
        }
Esempio n. 2
0
        /// <summary>
        ///     Decodes the specified region of the buffer into an unadjusted frame length.  The default implementation is
        ///     capable of decoding the specified region into an unsigned 8/16/24/32/64 bit integer.  Override this method to
        ///     decode the length field encoded differently.
        ///     Note that this method must not modify the state of the specified buffer (e.g.
        ///     <see cref="IByteBuffer.ReaderIndex" />,
        ///     <see cref="IByteBuffer.WriterIndex" />, and the content of the buffer.)
        /// </summary>
        /// <param name="buffer">The buffer we'll be extracting the frame length from.</param>
        /// <param name="offset">The offset from the absolute <see cref="IByteBuffer.ReaderIndex" />.</param>
        /// <param name="length">The length of the framelenght field. Expected: 1, 2, 3, 4, or 8.</param>
        /// <param name="order">The preferred <see cref="ByteOrder" /> of <see cref="buffer" />.</param>
        /// <returns>A long integer that represents the unadjusted length of the next frame.</returns>
        protected long GetUnadjustedFrameLength(IByteBuffer buffer, int offset, int length, ByteOrder order)
        {
            buffer = buffer.WithOrder(order);
            long frameLength;

            switch (length)
            {
            case 1:
                frameLength = buffer.GetByte(offset);
                break;

            case 2:
                frameLength = buffer.GetShort(offset);
                break;

            case 4:
                frameLength = buffer.GetInt(offset);
                break;

            case 8:
                frameLength = buffer.GetLong(offset);
                break;

            default:
                throw new DecoderException("unsupported lengthFieldLength: " + this.lengthFieldLength + " (expected: 1, 2, 3, 4, or 8)");
            }
            return(frameLength);
        }
Esempio n. 3
0
 public static uint GetUnsignedInt(this IByteBuffer buf, int index)
 {
     unchecked
     {
         return((uint)(buf.GetInt(index)));
     }
 }
Esempio n. 4
0
        public MsgPacket(IByteBuffer byteBuf)
        {
            int len = byteBuf.GetInt(0);

            this.data = new byte[len];
            byteBuf.ReadBytes(this.data);
        }
Esempio n. 5
0
        /// <summary>
        ///     Calculates the hash code of the specified buffer.  This method is
        ///     useful when implementing a new buffer type.
        /// </summary>
        public static int HashCode(IByteBuffer buffer)
        {
            int aLen      = buffer.ReadableBytes;
            int intCount  = (int)((uint)aLen >> 2);
            int byteCount = aLen & 3;

            int hashCode   = 1;
            int arrayIndex = buffer.ReaderIndex;

            for (int i = intCount; i > 0; i--)
            {
                hashCode    = 31 * hashCode + buffer.GetInt(arrayIndex);
                arrayIndex += 4;
            }

            for (int i = byteCount; i > 0; i--)
            {
                hashCode = 31 * hashCode + buffer.GetByte(arrayIndex++);
            }

            if (hashCode == 0)
            {
                hashCode = 1;
            }

            return(hashCode);
        }
        /// <summary>
        ///     Decodes the specified region of the buffer into an unadjusted frame length.  The default implementation is
        ///     capable of decoding the specified region into an unsigned 8/16/24/32/64 bit integer.  Override this method to
        ///     decode the length field encoded differently.
        ///     Note that this method must not modify the state of the specified buffer (e.g.
        ///     <see cref="IByteBuffer.ReaderIndex" />,
        ///     <see cref="IByteBuffer.WriterIndex" />, and the content of the buffer.)
        /// </summary>
        /// <param name="buffer">The buffer we'll be extracting the frame length from.</param>
        /// <param name="offset">The offset from the absolute <see cref="IByteBuffer.ReaderIndex" />.</param>
        /// <param name="length">The length of the framelenght field. Expected: 1, 2, 3, 4, or 8.</param>
        /// <param name="order">The preferred <see cref="ByteOrder" /> of buffer.</param>
        /// <returns>A long integer that represents the unadjusted length of the next frame.</returns>
        protected virtual long GetUnadjustedFrameLength(IByteBuffer buffer, int offset, int length, ByteOrder order)
        {
            long frameLength;

            switch (length)
            {
            case 1:
                frameLength = buffer.GetByte(offset);
                break;

            case 2:
                frameLength = order == ByteOrder.BigEndian ? buffer.GetUnsignedShort(offset) : buffer.GetUnsignedShortLE(offset);
                break;

            case 3:
                frameLength = order == ByteOrder.BigEndian ? buffer.GetUnsignedMedium(offset) : buffer.GetUnsignedMediumLE(offset);
                break;

            case 4:
                frameLength = order == ByteOrder.BigEndian ? buffer.GetInt(offset) : buffer.GetIntLE(offset);
                break;

            case 8:
                frameLength = order == ByteOrder.BigEndian ? buffer.GetLong(offset) : buffer.GetLongLE(offset);
                break;

            default:
                throw new DecoderException("unsupported lengthFieldLength: " + this.lengthFieldLength + " (expected: 1, 2, 3, 4, or 8)");
            }
            return(frameLength);
        }
Esempio n. 7
0
        /// <summary>
        ///     Calculates the hash code of the specified buffer.  This method is
        ///     useful when implementing a new buffer type.
        /// </summary>
        public static int HashCode(IByteBuffer buffer)
        {
            int aLen      = buffer.ReadableBytes;
            int intCount  = aLen.RightUShift(2);
            int byteCount = aLen & 3;

            int hashCode   = EmptyByteBuffer.EmptyByteBufferHashCode;
            int arrayIndex = buffer.ReaderIndex;

            for (int i = intCount; i > 0; i--)
            {
                hashCode    = 31 * hashCode + buffer.GetInt(arrayIndex);
                arrayIndex += 4;
            }

            for (int i = byteCount; i > 0; i--)
            {
                hashCode = 31 * hashCode + buffer.GetByte(arrayIndex++);
            }

            if (0u >= (uint)hashCode)
            {
                hashCode = 1;
            }

            return(hashCode);
        }
        void Unmask(IByteBuffer frame)
        {
            int i   = frame.ReaderIndex;
            int end = frame.WriterIndex;

            int intMask = BitConverter.IsLittleEndian
                ? (this.maskingKey[0])
                          | (this.maskingKey[1] << 8)
                          | (this.maskingKey[2] << 16)
                          | (this.maskingKey[3] << 24)
                : (this.maskingKey[0] << 24)
                          | (this.maskingKey[1] << 16)
                          | (this.maskingKey[2] << 8)
                          | this.maskingKey[3];

            for (; i + 3 < end; i += 4)
            {
                int unmasked = frame.GetInt(i) ^ intMask;
                frame.SetInt(i, unmasked);
            }
            for (; i < end; i++)
            {
                frame.SetByte(i, frame.GetByte(i) ^ this.maskingKey[i % 4]);
            }
        }
Esempio n. 9
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer cumulationBuff, List <object> output)
        {
            bool isParse = true;

            while (isParse)
            {
                isParse = false;
                if (Status == 0 && cumulationBuff.ReadableBytes >= HEADER_LENGTH)//解析head
                {
                    bodyLength = cumulationBuff.GetInt(cumulationBuff.ReaderIndex + 4);
                    Status     = 1;

                    if (bodyLength > cumulationBuff.MaxCapacity)
                    {
                        throw new Exception("包长超过最大值");
                    }
                }
                if (Status == 1 && cumulationBuff.ReadableBytes >= bodyLength + HEADER_LENGTH)  //解析body
                {
                    byte[] frameData = cumulationBuff.ReadeBytes(cumulationBuff.ReaderIndex, bodyLength + HEADER_LENGTH);
                    Status = 0;

                    output.Add(Decode(frameData));
                    isParse = true;
                }
            }//while
        }
        protected override long GetUnadjustedFrameLength(IByteBuffer buffer, int offset, int length, ByteOrder order)
        {
            buffer = buffer.WithOrder(order);
            var scalarPrefix = buffer.GetByte(offset++);

            if (buffer.ReadableBytes - (offset - buffer.ReaderIndex) < scalarPrefix)
            {
                return(scalarPrefix);
            }

            switch (scalarPrefix)
            {
            case 1:
                return(buffer.GetByte(offset) + scalarPrefix);

            case 2:
                return(buffer.GetShort(offset) + scalarPrefix);

            case 4:
                return(buffer.GetInt(offset) + scalarPrefix);

            default:
                throw new ProudException("Invalid scalar prefix " + scalarPrefix);
            }
        }
 /// <summary>
 ///     Decodes the specified region of the buffer into an unadjusted frame length.  The default implementation is
 ///     capable of decoding the specified region into an unsigned 8/16/24/32/64 bit integer.  Override this method to
 ///     decode the length field encoded differently.
 ///     Note that this method must not modify the state of the specified buffer (e.g.
 ///     <see cref="IByteBuffer.ReaderIndex" />,
 ///     <see cref="IByteBuffer.WriterIndex" />, and the content of the buffer.)
 /// </summary>
 /// <param name="buffer">The buffer we'll be extracting the frame length from.</param>
 /// <param name="offset">The offset from the absolute <see cref="IByteBuffer.ReaderIndex" />.</param>
 /// <param name="length">The length of the framelenght field. Expected: 1, 2, 3, 4, or 8.</param>
 /// <returns>A long integer that represents the unadjusted length of the next frame.</returns>
 protected static long GetUnadjustedFrameLength(IByteBuffer buffer, int offset, int length)
 {
     return(length switch
     {
         1 => buffer.GetByte(offset),
         2 => buffer.GetUnsignedShort(offset),
         3 => buffer.GetUnsignedMedium(offset),
         4 => buffer.GetInt(offset),
         8 => buffer.GetLong(offset),
         _ => CThrowHelper.ThrowDecoderException(length),
     });
Esempio n. 12
0
        protected IByteBuffer TryDecodeFramedMessage(IChannelHandlerContext ctx,
                                                     IChannel channel,
                                                     IByteBuffer buffer,
                                                     bool stripFraming)
        {
            // Framed messages are prefixed by the size of the frame (which doesn't include the
            // framing itself).

            int messageStartReaderIndex = buffer.ReaderIndex;
            int messageContentsOffset;

            if (stripFraming)
            {
                messageContentsOffset = messageStartReaderIndex + MessageFrameSize;
            }
            else
            {
                messageContentsOffset = messageStartReaderIndex;
            }

            // The full message is larger by the size of the frame size prefix
            int messageLength         = buffer.GetInt(messageStartReaderIndex) + MessageFrameSize;
            int messageContentsLength = messageStartReaderIndex + messageLength - messageContentsOffset;

            if (messageContentsLength > _maxFrameSize)
            {
                ctx.FireExceptionCaught(
                    new TooLongFrameException("Maximum frame size of " + _maxFrameSize +
                                              " exceeded")
                    );
            }

            if (messageLength == 0)
            {
                // Zero-sized frame: just ignore it and return nothing
                buffer.SetReaderIndex(messageContentsOffset);
                return(null);
            }
            else if (buffer.ReadableBytes < messageLength)
            {
                // Full message isn't available yet, return nothing for now
                return(null);
            }
            else
            {
                // Full message is available, return it
                IByteBuffer messageBuffer = ExtractFrame(buffer,
                                                         messageContentsOffset,
                                                         messageContentsLength);
                buffer.SetReaderIndex(messageStartReaderIndex + messageLength);
                return(messageBuffer);
            }
        }
Esempio n. 13
0
        public List <Message> AddAndGetMessage(IByteBuffer byteBuf)
        {
            List <Message> list = new List <Message>();

            if (cumulationBuff == null)
            {
                cumulationBuff = byteBuf;
            }
            else
            {
                cumulationBuff.WriteBytes(byteBuf.ReadeBytes());
            }

            bool isParse = true;

            while (isParse)
            {
                isParse = false;
                if (Status == 0 && cumulationBuff.ReadableBytes >= HEADER_LENGTH)//解析head
                {
                    bodyLength = cumulationBuff.GetInt(cumulationBuff.ReaderIndex + 4);
                    Status     = 1;

                    if (bodyLength > cumulationBuff.MaxCapacity)
                    {
                        throw new Exception("包长超过最大值");
                    }
                }
                if (Status == 1 && cumulationBuff.ReadableBytes >= bodyLength + HEADER_LENGTH)  //解析body
                {
                    byte[] frameData = cumulationBuff.ReadeBytes(cumulationBuff.ReaderIndex, bodyLength + HEADER_LENGTH);
                    Status = 0;

                    list.Add(Decode(frameData));
                    isParse = true;
                }
            }//while

            if (list.Count > 0)
            {
                if (cumulationBuff != null && !cumulationBuff.IsReadable())
                {
                    cumulationBuff = null;
                }
                else
                {
                    cumulationBuff.DiscardReadBytes();
                }
            }

            return(list);
        }
Esempio n. 14
0
        /// <summary>
        /// Decryptes data using XTEA.
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="keys"></param>
        /// <returns></returns>
        private static IByteBuffer DecryptXTEA(IByteBuffer buffer, int start, int end, int[] keys)
        {
            int length = (end - start) / 8;

            for (int index = 0; index < length; index++)
            {
                int v1     = buffer.GetInt(start + index * 8);
                int v0     = buffer.GetInt(start + index * 8 + 4);
                int ratio  = unchecked ((int)0x9e3779b9);
                int rounds = 32;
                int offset = ratio * rounds;
                while (rounds-- > 0)
                {
                    v0     -= (((int)((uint)v1 >> -1563092443) ^ v1 << 611091524) + v1 ^ offset + keys[(int)((uint)offset >> -1002502837) & 0x56c00003]);
                    offset -= ratio;
                    v1     -= (((int)((uint)v0 >> 1337206757) ^ v0 << 363118692) - -v0 ^ offset + keys[offset & 0x3]);
                }
                buffer.SetInt(start + index * 8, v1);
                buffer.SetInt(start + index * 8 + 4, v0);
            }
            return(buffer);
        }
Esempio n. 15
0
        void Unmask(IByteBuffer frame)
        {
            int i   = frame.ReaderIndex;
            int end = frame.WriterIndex;

            int intMask = (this.maskingKey[0] << 24)
                          | (this.maskingKey[1] << 16)
                          | (this.maskingKey[2] << 8)
                          | this.maskingKey[3];

            for (; i + 3 < end; i += 4)
            {
                int unmasked = frame.GetInt(i) ^ intMask;
                _ = frame.SetInt(i, unmasked);
            }
            for (; i < end; i++)
            {
                _ = frame.SetByte(i, frame.GetByte(i) ^ this.maskingKey[i % 4]);
            }
        }
Esempio n. 16
0
        protected override long GetUnadjustedFrameLength(IByteBuffer buffer, int offset, int length, ByteOrder order)
        {
            buffer = buffer.WithOrder(ByteOrder.LittleEndian);
            var scalarPrefix = buffer.GetByte(offset++);

            switch (scalarPrefix)
            {
            case 1:
                return(buffer.ReadableBytes < 1 ? 1 : buffer.GetByte(offset) + 1);

            case 2:
                return(buffer.ReadableBytes < 2 ? 2 : buffer.GetShort(offset) + 2);

            case 4:
                return(buffer.ReadableBytes < 4 ? 4 : buffer.GetInt(offset) + 4);

            default:
                throw new ProudException("Invalid scalar prefix " + scalarPrefix);
            }
        }
Esempio n. 17
0
        protected override long GetUnadjustedFrameLength(IByteBuffer buffer, int offset, int length, ByteOrder order)
        {
            buffer = buffer.WithOrder(ByteOrder.LittleEndian);
            var scalarPrefix = buffer.GetByte(offset++);

            // lengthFieldOffset from constructor + scalarPrefix from above
            var bytesLeft = buffer.ReadableBytes - Math.Abs(buffer.ReaderIndex - offset) + 1;

            switch (scalarPrefix)
            {
            case 1:
                return(bytesLeft < 1 ? 1 : buffer.GetByte(offset) + 1);

            case 2:
                return(bytesLeft < 2 ? 2 : buffer.GetShort(offset) + 2);

            case 4:
                return(bytesLeft < 4 ? 4 : buffer.GetInt(offset) + 4);

            default:
                throw new ProudException("Invalid scalar prefix " + scalarPrefix);
            }
        }
Esempio n. 18
0
        protected override void Decode(IChannelHandlerContext channelHandlerContext, IByteBuffer byteBuf, List <Object> list)
        {
            if (byteBuf.ReadableBytes < HeadSize)
            {
                return;
            }

            int length = byteBuf.GetInt(byteBuf.ReaderIndex + LengthOffset); // 获取取消息内容长度

            if (byteBuf.ReadableBytes < length)
            {
                return;
            }

            int readerIndex = byteBuf.ReaderIndex;

            IByteBuffer frame = byteBuf.Slice(readerIndex, length);

            frame.Retain();
            byteBuf.SetReaderIndex(readerIndex + length);

            list.Add(frame);
        }
Esempio n. 19
0
        /// <summary>
        ///     Decodes the specified region of the buffer into an unadjusted frame length.  The default implementation is
        ///     capable of decoding the specified region into an unsigned 8/16/24/32/64 bit integer.  Override this method to
        ///     decode the length field encoded differently.
        ///     Note that this method must not modify the state of the specified buffer (e.g.
        ///     <see cref="IByteBuffer.ReaderIndex" />,
        ///     <see cref="IByteBuffer.WriterIndex" />, and the content of the buffer.)
        /// </summary>
        /// <param name="buffer">The buffer we'll be extracting the frame length from.</param>
        /// <param name="offset">The offset from the absolute <see cref="IByteBuffer.ReaderIndex" />.</param>
        /// <param name="length">The length of the framelenght field. Expected: 1, 2, 3, 4, or 8.</param>
        /// <param name="order">The preferred <see cref="ByteOrder" /> of buffer.</param>
        /// <returns>A long integer that represents the unadjusted length of the next frame.</returns>
        protected long GetUnadjustedFrameLength(IByteBuffer buffer, int offset, int length, ByteOrder order)
        {
            long frameLength;

            switch (length)
            {
            case 1:
                frameLength = buffer.GetByte(offset);
                break;

            case 2:
                frameLength = order == ByteOrder.BigEndian ? buffer.GetUnsignedShort(offset) : buffer.GetUnsignedShortLE(offset);
                break;

            case 3:
                frameLength = order == ByteOrder.BigEndian ? buffer.GetUnsignedMedium(offset) : buffer.GetUnsignedMediumLE(offset);
                break;

            case 4:
                frameLength = order == ByteOrder.BigEndian ? buffer.GetInt(offset) : buffer.GetIntLE(offset);
                break;

            case 8:
                frameLength = order == ByteOrder.BigEndian ? buffer.GetLong(offset) : buffer.GetLongLE(offset);
                break;

            default:
                throw new DecoderException("unsupported lengthFieldLength: " + this.lengthFieldLength + " (expected: 1, 2, 3, 4, or 8)");
            }
            byte[] bytes = BitConverter.GetBytes(frameLength);

            string slength = Encoding.UTF8.GetString(bytes);

            frameLength = long.Parse(slength);

            return(frameLength);
        }
Esempio n. 20
0
        /// <summary>
        /// Calculates the hash code of the specified buffer.  This method is
        /// useful when implementing a new buffer type.
        /// </summary>
        public static int HashCode(IByteBuffer buffer)
        {
            int aLen = buffer.ReadableBytes;
            int intCount = (int)((uint)aLen >> 2);
            int byteCount = aLen & 3;

            int hashCode = 1;
            int arrayIndex = buffer.ReaderIndex;
            if (buffer.Order == ByteOrder.BigEndian)
            {
                for (int i = intCount; i > 0; i--)
                {
                    hashCode = 31 * hashCode + buffer.GetInt(arrayIndex);
                    arrayIndex += 4;
                }
            }
            else
            {
                for (int i = intCount; i > 0; i--)
                {
                    hashCode = 31 * hashCode + SwapInt(buffer.GetInt(arrayIndex));
                    arrayIndex += 4;
                }
            }

            for (int i = byteCount; i > 0; i--)
            {
                hashCode = 31 * hashCode + buffer.GetByte(arrayIndex++);
            }

            if (hashCode == 0)
            {
                hashCode = 1;
            }

            return hashCode;
        }
Esempio n. 21
0
        public override unsafe void Encode(IChannelHandlerContext ctx, WebSocketFrame msg, List <object> output)
        {
            IByteBuffer data = msg.Content;
            var         mask = stackalloc byte[4];

            byte opcode = 0;

            if (msg is TextWebSocketFrame)
            {
                opcode = OpcodeText;
            }
            else if (msg is PingWebSocketFrame)
            {
                opcode = OpcodePing;
            }
            else if (msg is PongWebSocketFrame)
            {
                opcode = OpcodePong;
            }
            else if (msg is CloseWebSocketFrame)
            {
                opcode = OpcodeClose;
            }
            else if (msg is BinaryWebSocketFrame)
            {
                opcode = OpcodeBinary;
            }
            else if (msg is ContinuationWebSocketFrame)
            {
                opcode = OpcodeCont;
            }
            else
            {
                ThrowNotSupportedException(msg);
            }

            int length = data.ReadableBytes;

            if (Logger.DebugEnabled)
            {
                Logger.Debug($"Encoding WebSocket Frame opCode={opcode} length={length}");
            }

            int b0 = 0;

            if (msg.IsFinalFragment)
            {
                b0 |= 1 << 7;
            }
            b0 |= msg.Rsv % 8 << 4;
            b0 |= opcode % 128;

            if (opcode == OpcodePing && length > 125)
            {
                ThrowTooLongFrameException(length);
            }

            bool        release = true;
            IByteBuffer buf     = null;

            try
            {
                int maskLength = this.maskPayload ? 4 : 0;
                if (length <= 125)
                {
                    int size = 2 + maskLength;
                    if (this.maskPayload || length <= GatheringWriteThreshold)
                    {
                        size += length;
                    }
                    buf = ctx.Allocator.Buffer(size);
                    buf.WriteByte(b0);
                    byte b = (byte)(this.maskPayload ? 0x80 | (byte)length : (byte)length);
                    buf.WriteByte(b);
                }
                else if (length <= 0xFFFF)
                {
                    int size = 4 + maskLength;
                    if (this.maskPayload || length <= GatheringWriteThreshold)
                    {
                        size += length;
                    }
                    buf = ctx.Allocator.Buffer(size);
                    buf.WriteByte(b0);
                    buf.WriteByte(this.maskPayload ? 0xFE : 126);
                    buf.WriteByte(length.RightUShift(8) & 0xFF);
                    buf.WriteByte(length & 0xFF);
                }
                else
                {
                    int size = 10 + maskLength;
                    if (this.maskPayload || length <= GatheringWriteThreshold)
                    {
                        size += length;
                    }
                    buf = ctx.Allocator.Buffer(size);
                    buf.WriteByte(b0);
                    buf.WriteByte(this.maskPayload ? 0xFF : 127);
                    buf.WriteLong(length);
                }

                // Write payload
                if (this.maskPayload)
                {
                    int intMask = (this.random.Next() * int.MaxValue);

                    // Mask bytes in BE
                    uint unsignedValue = (uint)intMask;
                    *    mask          = (byte)(unsignedValue >> 24);
                    *(mask + 1) = (byte)(unsignedValue >> 16);
                    *(mask + 2) = (byte)(unsignedValue >> 8);
                    *(mask + 3) = (byte)unsignedValue;

                    // Mask in BE
                    buf.WriteInt(intMask);

                    int counter = 0;
                    int i       = data.ReaderIndex;
                    int end     = data.WriterIndex;

                    for (; i + 3 < end; i += 4)
                    {
                        int intData = data.GetInt(i);
                        buf.WriteInt(intData ^ intMask);
                    }
                    for (; i < end; i++)
                    {
                        byte byteData = data.GetByte(i);
                        buf.WriteByte(byteData ^ mask[counter++ % 4]);
                    }
                    output.Add(buf);
                }
                else
                {
                    if (buf.WritableBytes >= data.ReadableBytes)
                    {
                        // merge buffers as this is cheaper then a gathering write if the payload is small enough
                        buf.WriteBytes(data);
                        output.Add(buf);
                    }
                    else
                    {
                        output.Add(buf);
                        output.Add(data.Retain());
                    }
                }
                release = false;
            }
            finally
            {
                if (release)
                {
                    buf?.Release();
                }
            }
        }
Esempio n. 22
0
 public static float GetFloat(this IByteBuffer buf, int index) => ByteBufferUtil.Int32BitsToSingle(buf.GetInt(index));
Esempio n. 23
0
 public virtual int GetInt(int index) => Buf.GetInt(index);
 /// <summary>
 ///     Decodes the specified region of the buffer into an unadjusted frame length.  The default implementation is
 ///     capable of decoding the specified region into an unsigned 8/16/24/32/64 bit integer.  Override this method to
 ///     decode the length field encoded differently.
 ///     Note that this method must not modify the state of the specified buffer (e.g.
 ///     <see cref="IByteBuffer.ReaderIndex" />,
 ///     <see cref="IByteBuffer.WriterIndex" />, and the content of the buffer.)
 /// </summary>
 /// <param name="buffer">The buffer we'll be extracting the frame length from.</param>
 /// <param name="offset">The offset from the absolute <see cref="IByteBuffer.ReaderIndex" />.</param>
 /// <param name="length">The length of the framelenght field. Expected: 1, 2, 3, 4, or 8.</param>
 /// <param name="order">The preferred <see cref="ByteOrder" /> of <see cref="buffer" />.</param>
 /// <returns>A long integer that represents the unadjusted length of the next frame.</returns>
 protected long GetUnadjustedFrameLength(IByteBuffer buffer, int offset, int length, ByteOrder order)
 {
     buffer = buffer.WithOrder(order);
     long frameLength;
     switch (length)
     {
         case 1:
             frameLength = buffer.GetByte(offset);
             break;
         case 2:
             frameLength = buffer.GetShort(offset);
             break;
         case 4:
             frameLength = buffer.GetInt(offset);
             break;
         case 8:
             frameLength = buffer.GetLong(offset);
             break;
         default:
             throw new DecoderException("unsupported lengthFieldLength: " + this.lengthFieldLength + " (expected: 1, 2, 3, 4, or 8)");
     }
     return frameLength;
 }
Esempio n. 25
0
        /// <summary>
        /// 解析消息包
        /// </summary>
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            try
            {
                //数据包长度为一个int至少4个字节
                if (input.ReadableBytes < 4)
                {
                    return;
                }

                //仅仅是Get没有Read
                int msgLen = input.GetInt(input.ReaderIndex);
                if (!CheckMsgLen(msgLen))
                {
                    context.CloseAsync();
                    return;
                }

                //如果接受数据不够,等待下次
                if (input.ReadableBytes < msgLen)
                {
                    return;
                }

                //在buffer中读取掉消息长度
                input.ReadInt();

                // 时间合法性检查
                long time = input.ReadLong();
                if (!CheckTime(context, time))
                {
                    context.CloseAsync();
                    return;
                }

                // 序列号检查
                int order = input.ReadInt();
                if (!CheckMagicNumber(context, order, msgLen))
                {
                    context.CloseAsync();
                    return;
                }

                //消息id
                int msgId = input.ReadInt();

                byte[] msgData = null;
                msgData = new byte[msgLen - 20];
                input.ReadBytes(msgData);

                var msg = TcpHandlerFactory.GetMsg(msgId);
                if (msg == null)
                {
                    LOGGER.Error("消息ID:{} 找不到对应的Msg.", msgId);
                    return;
                }
                else
                {
                    if (msg.GetMsgId() == msgId)
                    {
                        msg.Deserialize(msgData);
                    }
                    else
                    {
                        LOGGER.Error("后台解析消息失败,注册消息id和消息无法对应.real:{0}, register:{1}", msg.GetMsgId(), msgId);
                        return;
                    }
                }
                output.Add(msg);
            }
            catch (Exception e)
            {
                LOGGER.Error(e, "解析数据异常," + e.Message + "\n" + e.StackTrace);
            }
        }
Esempio n. 26
0
 public int GetInt(int index)
 {
     CheckIndex(index, 4);
     return(_buffer.GetInt(index));
 }
Esempio n. 27
0
        /// <summary>
        /// Compares the two specified buffers as described in {@link ByteBuf#compareTo(ByteBuf)}.
        /// This method is useful when implementing a new buffer type.
        /// </summary>
        public static int Compare(IByteBuffer bufferA, IByteBuffer bufferB)
        {
            int aLen      = bufferA.ReadableBytes;
            int bLen      = bufferB.ReadableBytes;
            int minLength = Math.Min(aLen, bLen);
            int uintCount = (int)((uint)minLength >> 2);
            int byteCount = minLength & 3;

            int aIndex = bufferA.ReaderIndex;
            int bIndex = bufferB.ReaderIndex;

            if (bufferA.Order == bufferB.Order)
            {
                for (int i = uintCount; i > 0; i--)
                {
                    long va = bufferA.GetUnsignedInt(aIndex);
                    long vb = bufferB.GetUnsignedInt(bIndex);
                    if (va > vb)
                    {
                        return(1);
                    }
                    if (va < vb)
                    {
                        return(-1);
                    }
                    aIndex += 4;
                    bIndex += 4;
                }
            }
            else
            {
                for (int i = uintCount; i > 0; i--)
                {
                    long va = bufferA.GetUnsignedInt(aIndex);
                    long vb = SwapInt(bufferB.GetInt(bIndex)) & 0xFFFFFFFFL;
                    if (va > vb)
                    {
                        return(1);
                    }
                    if (va < vb)
                    {
                        return(-1);
                    }
                    aIndex += 4;
                    bIndex += 4;
                }
            }

            for (int i = byteCount; i > 0; i--)
            {
                short va = bufferA.GetByte(aIndex);
                short vb = bufferB.GetByte(bIndex);
                if (va > vb)
                {
                    return(1);
                }
                if (va < vb)
                {
                    return(-1);
                }
                aIndex++;
                bIndex++;
            }

            return(aLen - bLen);
        }
Esempio n. 28
0
        /// <summary>
        /// Compares the two specified buffers as described in {@link ByteBuf#compareTo(ByteBuf)}.
        /// This method is useful when implementing a new buffer type.
        /// </summary>
        public static int Compare(IByteBuffer bufferA, IByteBuffer bufferB)
        {
            int aLen = bufferA.ReadableBytes;
            int bLen = bufferB.ReadableBytes;
            int minLength = Math.Min(aLen, bLen);
            int uintCount = (int)((uint)minLength >> 2);
            int byteCount = minLength & 3;

            int aIndex = bufferA.ReaderIndex;
            int bIndex = bufferB.ReaderIndex;

            if (bufferA.Order == bufferB.Order)
            {
                for (int i = uintCount; i > 0; i--)
                {
                    long va = bufferA.GetUnsignedInt(aIndex);
                    long vb = bufferB.GetUnsignedInt(bIndex);
                    if (va > vb)
                    {
                        return 1;
                    }
                    if (va < vb)
                    {
                        return -1;
                    }
                    aIndex += 4;
                    bIndex += 4;
                }
            }
            else
            {
                for (int i = uintCount; i > 0; i--)
                {
                    long va = bufferA.GetUnsignedInt(aIndex);
                    long vb = SwapInt(bufferB.GetInt(bIndex)) & 0xFFFFFFFFL;
                    if (va > vb)
                    {
                        return 1;
                    }
                    if (va < vb)
                    {
                        return -1;
                    }
                    aIndex += 4;
                    bIndex += 4;
                }
            }

            for (int i = byteCount; i > 0; i--)
            {
                short va = bufferA.GetByte(aIndex);
                short vb = bufferB.GetByte(bIndex);
                if (va > vb)
                {
                    return 1;
                }
                if (va < vb)
                {
                    return -1;
                }
                aIndex++;
                bIndex++;
            }

            return aLen - bLen;
        }