public void TestResponseParsing()
        {
            Message response = new Response(StatusCode.Content);

            response.Type  = MessageType.NON;
            response.ID    = 9;
            response.Token = new byte[] { 22, 255, 0, 78, 100, 22 };
            response.AddETag(new byte[] { 1, 0, 0, 0, 0, 1 })
            .AddLocationPath("/one/two/three/four/five/six/seven/eight/nine/ten")
            .AddOption(Option.Create((OptionType)57453, "Arbitrary".GetHashCode()))
            .AddOption(Option.Create((OptionType)19205, "Arbitrary1"))
            .AddOption(Option.Create((OptionType)19205, "Arbitrary2"))
            .AddOption(Option.Create((OptionType)19205, "Arbitrary3"));

            byte[] bytes = Spec.NewMessageEncoder().Encode(response);

            IMessageDecoder decoder = Spec.NewMessageDecoder(bytes);

            Assert.IsTrue(decoder.IsResponse);

            Message result = decoder.Decode();

            Assert.AreEqual(response.ID, result.ID);
            Assert.IsTrue(response.Token.SequenceEqual(result.Token));
            Assert.IsTrue(response.GetOptions().SequenceEqual(result.GetOptions()));
        }
        public void Should_decode_single_lengthFramed_message()
        {
            var binaryContent = Encoding.UTF8.GetBytes("somebytes");
            var expectedBytes = binaryContent.Length;

            var data = Unpooled.Buffer(expectedBytes).WriteBytes(binaryContent);

            List <IByteBuf> encodedMessages;

            Encoder.Encode(TestConnection, data, out encodedMessages);

            List <IByteBuf> decodedMessages;

            Decoder.Decode(TestConnection, encodedMessages[0], out decodedMessages);

            Assert.True(binaryContent.SequenceEqual(decodedMessages[0].ToArray()));
        }
        public virtual Task <IMessage> ReadAsync()
        {
            if (reader == null)
            {
                throw new IOException("The channel is not connected.");
            }

            return(decoder.Decode(reader));
        }
Exemple #4
0
        public virtual async Task <IMessage> ReadAsync()
        {
            if (reader == null)
            {
                throw new IOException("The channel is not connected.");
            }

            return(await decoder.Decode(reader).ConfigureAwait(false));
        }
Exemple #5
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var buffer = (IByteBuffer)message;
            var data   = new byte[buffer.ReadableBytes];

            buffer.ReadBytes(data);
            var transportMessage = _messageDecoder.Decode(data);

            context.FireChannelRead(transportMessage);
            ReferenceCountUtil.Release(buffer);
        }
Exemple #6
0
 public void OnMessageReceived(byte[] dataBytes)
 {
     lock (receviedMessageList)
     {
         if (messageDecoder.Decode(dataBytes, out int messageId, out byte[] body))
         {
             ClientReceviedMessage receviedMessage = receviedMessagePool.Get();
             receviedMessage.Id   = messageId;
             receviedMessage.Body = body;
             receviedMessageList.Add(receviedMessage);
         }
Exemple #7
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var buffer = (IByteBuffer)message;
            var data   = new byte[buffer.ReadableBytes];

            buffer.ReadBytes(data);

            //Counter.Received(buffer.ReadableBytes);
            var microMessage = _messageDecoder.Decode <T>(data, _gzip);

            context.FireChannelRead(microMessage);
            ReferenceCountUtil.Release(buffer);
        }
 public void OnMessageReceived(Guid guid, byte[] dataBytes)
 {
     if (messageDecoder.Decode(dataBytes, out int messageId, out byte[] messageBody))
     {
         lock (receviedMessageList)
         {
             ServerReceivedMessage receviedMessage = receviedMessagePool.Get();
             receviedMessage.SessionId   = guid;
             receviedMessage.MessageId   = messageId;
             receviedMessage.MessageBody = messageBody;
             receviedMessageList.Add(receviedMessage);
         }
     }
Exemple #9
0
        public void ShouldDecodeSingleMessage()
        {
            var binaryContent = Encoding.ASCII.GetBytes("somebytes");
            var expectedBytes = binaryContent.Length;

            var data = ByteBuffer.AllocateDirect(expectedBytes).WriteBytes(binaryContent);

            List <IByteBuf> encodedMessages;

            Encoder.Encode(TestConnection, data, out encodedMessages);

            List <IByteBuf> decodedMessages;

            Decoder.Decode(TestConnection, encodedMessages[0], out decodedMessages);

            Assert.IsTrue(binaryContent.SequenceEqual(decodedMessages[0].ToArray()));
        }
        public void TestEmptyParsing()
        {
            Message signal = new EmptyMessage(MessageType.RST);

            signal.Type  = MessageType.NON;
            signal.ID    = 15;
            signal.Token = new byte[] { 33, 3, 5, 0, 39, 40 };

            byte[] bytes = Spec.NewMessageEncoder().Encode(signal);

            IMessageDecoder decoder = Spec.NewMessageDecoder(bytes);

            Assert.IsTrue(decoder.IsEmpty);

            Message result = decoder.Decode();

            Assert.AreEqual(signal.ID, result.ID);
            Assert.IsTrue(signal.Token.SequenceEqual(result.Token));
            Assert.IsTrue(signal.GetOptions().SequenceEqual(result.GetOptions()));
        }
Exemple #11
0
        private async Task MessageHandle(object ctx)
        {
            var             context = (MessageContext)ctx;
            ReceivedMessage msg     = null;

            try
            {
                msg = _messageDecoder.Decode(context);
            }
            catch (Exception ex)
            {
                _logger.DecodeError(context, ex);

                HandleError(_serviceProvider, new FailContext
                {
                    Raw = Encoding.UTF8.GetString(context.Content),
                    ExceptionMessage = ex.Message
                });

                return;
            }

            try
            {
                await _receivedEventPersistenter.InsertAsync(msg);
            }
            catch (Exception e)
            {
                _logger.ReceivedEventPersistenterInsert(msg, e);

                HandleError(_serviceProvider, new FailContext
                {
                    ExceptionMessage = e.Message,
                    Raw = Encoding.UTF8.GetString(context.Content),
                });

                return;
            }

            var result = false;

            try
            {
                var invoker = new DefaultConsumerInvoker(_serviceProvider, context);
                result = await invoker.InvokeAsync();

                _logger.LogInformation($"invoke result: {result} message: {msg.ToJson()}");
            }
            catch (Exception ex)
            {
                _logger.InvokeConsumer(context, msg, ex);
            }
            finally
            {
                if (result)
                {
                    try
                    {
                        await _receivedEventPersistenter.ChangeStateAsync(msg.MessageId, msg.TransactId, msg.Group, Core.State.MessageState.Succeeded);
                    }
                    catch (Exception ex)
                    {
                        _logger.UpdateReceivedMessage(msg, ex);
                    }
                    _logger.LogInformation($"message invoke true {msg.ToJson()}");
                }
                else
                {
                    _logger.LogInformation($"invoke false {msg.ToJson()}");

                    try
                    {
                        await _receivedEventPersistenter.ChangeStateAsync(msg.MessageId, msg.TransactId, msg.Group, Core.State.MessageState.Failed);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(110, ex, $"fail to update received message[ignore]: {msg.ToJson()}");
                    }

                    HandleError(_serviceProvider, new FailContext
                    {
                        ExceptionMessage = "",
                        State            = msg,
                    });
                }
            }
        }
Exemple #12
0
        /// <summary> 解码 </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="decoder"></param>
        /// <param name="data"></param>
        /// <param name="gzip"></param>
        /// <returns></returns>
        public static T Decode <T>(this IMessageDecoder decoder, byte[] data, bool gzip = true)
        {
            var obj = decoder.Decode(data, typeof(T), gzip);

            return(obj.CastTo <T>());
        }
            protected override bool DoDecode(ByteBuffer input, IProtocolDecoderOutput output)
            {
                MessageDecoderResult result;

                if (_currentDecoder == null)
                {
                    IMessageDecoder[] decoders = _decoders;
                    int undecodables           = 0;

                    for (int i = decoders.Length - 1; i >= 0; i--)
                    {
                        IMessageDecoder decoder = decoders[i];
                        int             limit   = input.Limit;
                        int             pos     = input.Position;

                        try
                        {
                            result = decoder.Decodable(input);
                        }
                        finally
                        {
                            input.Position = pos;
                            input.Limit    = limit;
                        }

                        if (result == MessageDecoderResult.OK)
                        {
                            _currentDecoder = decoder;
                            break;
                        }
                        else if (result == MessageDecoderResult.NOT_OK)
                        {
                            undecodables++;
                        }
                        else if (result != MessageDecoderResult.NEED_DATA)
                        {
                            throw new Exception("Unexpected decode result (see your decodable()): " + result);
                        }
                    }

                    if (undecodables == _decoders.Length)
                    {
                        // Throw an exception if all decoders cannot decode data.
                        input.Position = input.Limit; // Skip data
                        throw new ProtocolDecoderException(
                                  "No appropriate message decoder: " + input.GetHexDump());
                    }

                    if (_currentDecoder == null)
                    {
                        // Decoder is not determined yet (i.e. we need more data)
                        return(false);
                    }
                }

                result = _currentDecoder.Decode(input, output);
                if (result == MessageDecoderResult.OK)
                {
                    _currentDecoder = null;
                    return(true);
                }
                else if (result == MessageDecoderResult.NEED_DATA)
                {
                    return(false);
                }
                else if (result == MessageDecoderResult.NOT_OK)
                {
                    throw new ProtocolDecoderException("Message decoder returned NOT_OK.");
                }
                else
                {
                    throw new Exception("Unexpected decode result (see your decode()): " + result);
                }
            }
Exemple #14
0
 public virtual Task <IMessage> ReadAsync()
 {
     return(decoder.Decode(reader));
 }