Example #1
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var msg = message as Message;

            if (msg == null)
            {
                context.FireChannelRead(message);
                return;
            }

            if (msg.MessageType == MessageType.Request || msg.MessageType == MessageType.Notify)
            {
                //var data = msg.Data;
                //var str = Encoding.UTF8.GetString(data);
                //// Console.WriteLine(str);
                //var count = Interlocked.Increment(ref Count);
                ////Console.WriteLine("接收数据:" + (count));
                //Logger.LogInformation("接收数据:" + count);

                //msg.MessageType = MessageType.Response;
                //context.Channel.WriteAsync(message).Wait();
                Task.Run(async() =>
                {
                    await BusinessProcess(context, msg);
                });
            }
            else
            {
                context.FireChannelRead(message);
            }
        }
Example #2
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var msg = message as Message;

            if (msg == null)
            {
                context.FireChannelRead(message);
                return;
            }

            if (msg.MessageType == MessageType.Response)
            {
                ResponseManage.Instance.SetResult(msg.RequestId, msg);

                /*
                 * var data = msg.Data;
                 * var str = Encoding.UTF8.GetString(data);
                 * var count = Interlocked.Increment(ref Count);
                 * // if(count % 10000==0 || count +10 >= 8000 * 10000)
                 * Logger.LogInformation("接收数据:" + (count));
                 * //Console.WriteLine(str);
                 */
            }
            else
            {
                context.FireChannelRead(message);
            }
        }
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     SafeProcess(() =>
     {
         var msg = (Message)message;
         if (msg.Type == MessageType.LoginResponse)
         {
             var result = CertifiedResult.FromMessage(msg);
             if (result.IsOK)
             {
                 //认证成功
                 Online(context);
                 context.FireChannelRead(msg);
             }
             else
             {
                 //认证失败
                 ClientEvents.AsyncRaiseError(this.Client, new LoginFailedException(result.Info));
                 context.CloseAsync();
             }
         }
         else
         {
             //不是登录认证的响应,那么交由下一个通道处理器
             context.FireChannelRead(msg);
         }
     }, context);
 }
Example #4
0
        protected override void ChannelRead0(IChannelHandlerContext ctx, ISocksMessage msg)
        {
            switch (msg.Version())
            {
            case SocksVersion.Socks4A:
                var socksV4CmdRequest = (ISocks4CommandRequest)msg;
                if (Equals(socksV4CmdRequest.Type, Socks4CommandType.Connect))
                {
                    ctx.Channel.Pipeline.AddLast(new SocksServerConnectHandler());
                    ctx.Channel.Pipeline.Remove(this);
                    ctx.FireChannelRead(msg);
                }
                else
                {
                    ctx.CloseAsync();
                }

                break;

            case SocksVersion.Socks5:
                if (msg is ISocks5InitialRequest)
                {
                    // auth support example
                    //ctx.pipeline().addFirst(new Socks5PasswordAuthRequestDecoder());
                    //ctx.write(new DefaultSocks5AuthMethodResponse(Socks5AuthMethod.PASSWORD));
                    ctx.Channel.Pipeline.AddFirst(new Socks5CommandRequestDecoder());
                    ctx.WriteAsync(new DefaultSocks5InitialResponse(Socks5AuthMethod.NoAuth));
                }
                else if (msg is ISocks5PasswordAuthRequest)
                {
                    ctx.Channel.Pipeline.AddFirst(new Socks5CommandRequestDecoder());
                    ctx.WriteAsync(new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.Success));
                }
                else if (msg is ISocks5CommandRequest)
                {
                    var socks5CmdRequest = (ISocks5CommandRequest)msg;
                    if (Equals(socks5CmdRequest.Type, Socks5CommandType.Connect))
                    {
                        ctx.Channel.Pipeline.AddLast(new SocksServerConnectHandler());
                        ctx.Channel.Pipeline.Remove(this);
                        ctx.FireChannelRead(msg);
                    }
                    else
                    {
                        ctx.CloseAsync();
                    }
                }
                else
                {
                    ctx.CloseAsync();
                }

                break;

            case SocksVersion.Unknown:
                ctx.CloseAsync();
                break;
            }
        }
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var data = message as IByteBuffer;

            if (data != null)
            {
                ThreadLocalObjectList output = ThreadLocalObjectList.NewInstance();
                try
                {
                    this.first = this.cumulation == null;
                    if (this.first)
                    {
                        this.cumulation = data;
                    }
                    else
                    {
                        this.cumulation = this.cumulator(context.Allocator, this.cumulation, data);
                    }
                    this.CallDecode(context, this.cumulation, output);
                }
                catch (DecoderException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw new DecoderException(ex);
                }
                finally
                {
                    if (this.cumulation != null && !this.cumulation.IsReadable())
                    {
                        this.cumulation.Release();
                        this.cumulation = null;
                    }
                    int size = output.Count;
                    this.decodeWasNull = size == 0;

                    for (int i = 0; i < size; i++)
                    {
                        context.FireChannelRead(output[i]);
                    }
                    output.Return();
                }
            }
            else
            {
                context.FireChannelRead(message);
            }
        }
Example #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var msg = (Message)message;

            //如果是握手应答消息,需要判断是否认证成功
            if (msg.Header != null && msg.Header.Type == MessageType.LOGIN_RESP)
            {
                if (loginResponseHandler != null)
                {
                    Task.Run(() =>
                    {
                        var channelName = context.GetChannelName();
                        loginResponseHandler(channelName, msg.Body, msg.Header.Attachments).ContinueWith(t =>
                        {
                            var loginResult = t.Result;
                            if (loginResult == 0)
                            {
                                logger.LogInformation($"Login success. Local={context.GetLocalNetString()}, Remote={context.GetRemoteNetString()}, Message={msg}");
                            }
                            else
                            {
                                logger.LogError($"Login failed. Local={context.GetLocalNetString()}, Remote={context.GetRemoteNetString()}, LoginResult={loginResult}");
                                //握手失败
                                context.CloseAsync();
                            }
                        });
                    });
                }
                else
                {
                    var loginResult = msg.Body;
                    if (loginResult.Length != 1 || loginResult[0] != (byte)0)
                    {
                        logger.LogError($"Login failed. Local={context.GetLocalNetString()}, Remote={context.GetRemoteNetString()}, LoginResult={loginResult[0]}");
                        //握手失败
                        context.CloseAsync();
                    }
                    else
                    {
                        logger.LogInformation($"Login success. Local={context.GetLocalNetString()}, Remote={context.GetRemoteNetString()}, Message={msg}");
                        context.FireChannelRead(message);
                    }
                }
            }
            else
            {
                context.FireChannelRead(message);
            }
        }
Example #7
0
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     if (message is IByteBuf)
     {
         var buf = (IByteBuf) message;
         var integer = buf.ReadInt();
         if (ReleaseMessages)
             ReferenceCountUtil.SafeRelease(message);
         context.FireChannelRead(integer);
     }
     else
     {
         context.FireChannelRead(message);
     }
 }
Example #8
0
 /// <summary>
 ///     The server should always correlate a response, if it can fire next pipeline, if not close the channel,
 ///     If the message is not a response (IE Request/Broadcast) it should pass on to the next handler without attempting to correlate.
 /// </summary>
 /// <param name="ctx"></param>
 /// <param name="message"></param>
 protected override void ChannelRead0(IChannelHandlerContext ctx, ProtocolMessage message)
 {
     Logger.Verbose("Received {message}", message);
     if (message.TypeUrl.EndsWith(MessageTypes.Response.Name))
     {
         if (_messageCorrelationManager.TryMatchResponse(message))
         {
             ctx.FireChannelRead(message);
         }
     }
     else
     {
         ctx.FireChannelRead(message);
     }
 }
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            IByteBuffer buffer = (IByteBuffer)message;

            try
            {
                byte[] data = new byte[buffer.ReadableBytes];
                buffer.GetBytes(buffer.ReaderIndex, data);

                string datajson     = LZ4MessagePackSerializer.ToJson(data);
                var    convertedMsg = _serializer.Deserialize <string, TransportMsg>(datajson);

                if (convertedMsg.ContentType == typeof(RemoteCallData).FullName)
                {
                    convertedMsg.Content = _serializer.Deserialize <object, RemoteCallData>(convertedMsg.Content);
                }
                else if (convertedMsg.ContentType == typeof(RemoteCallBackData).FullName)
                {
                    convertedMsg.Content = _serializer.Deserialize <object, RemoteCallBackData>(convertedMsg.Content);
                }
                context.FireChannelRead(convertedMsg);
            }
            finally
            {
                buffer.Release();
            }
        }
Example #10
0
            public override void ChannelRead(IChannelHandlerContext context, object message)
            {
                var t = _thread;

                if (t is null)
                {
                    _thread = Thread.CurrentThread;
                }
                else
                {
                    Assert.Same(t, Thread.CurrentThread);
                }

                IByteBuffer m     = (IByteBuffer)message;
                int         count = m.ReadableBytes / 4;

                for (int j = 0; j < count; j++)
                {
                    int actual   = m.ReadInt();
                    int expected = _inCnt++;
                    Assert.Equal(expected, actual);
                    context.FireChannelRead(actual);
                }
                m.Release();
            }
Example #11
0
        /// <param name="ctx"></param>
        /// <param name="msg"></param>
        public override void ChannelRead(IChannelHandlerContext ctx, object msg)
        {
            var release = true;

            try
            {
                if (msg is T msg1)
                {
                    ChannelRead0(ctx, msg1);
                }
                else
                {
                    release = false;
                    ctx.FireChannelRead(msg);
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
            }
            finally
            {
                if (_autoRelease && release)
                {
                    ReferenceCountUtil.Release(msg);
                }
            }
        }
Example #12
0
            public override void ChannelRead(IChannelHandlerContext context, object msg)
            {
                bool release = true;

                try
                {
                    if (msg is IPacket packet)
                    {
                        _messageRouter.Route(new RequestContext()
                        {
                            Request = packet
                        });
                    }
                    else
                    {
                        release = false;
                        context.FireChannelRead(msg);
                    }
                }
                finally
                {
                    if (_autoRelease && release)
                    {
                        ReferenceCountUtil.Release(msg);
                    }
                }
            }
        /// <inheritdoc />
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var buffer = message as IByteBuffer;

            if (buffer == null)
            {
                return;
            }
            var b = buffer.GetByte(buffer.ReaderIndex);

            switch (b)
            {
            case SocksProtocolVersion.Socks4A:
                context.Channel.Pipeline.Replace(this, nameof(Socks4ServerHandler), new Socks4ServerHandler());
                break;

            case SocksProtocolVersion.Socks5:
                context.Channel.Pipeline.Replace(this, nameof(Socks5ServerHandler), new Socks5ServerHandler());
                break;

            default:
                Logger.LogError("Unknow socks verion protocol.");
                break;
            }
            context.FireChannelRead(message);
        }
Example #14
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            if (input is EmptyByteBuffer)
            {
                return;
            }

            if (input.GetLongLE(0) != 0)
            {
                context.FireChannelRead(input.Retain());

                return;
            }

            input.SkipBytes(8);

            var messageId = input.ReadLongLE();

            input.SkipBytes(4);

            var message = Serializer.Deserialize(input);

            Log.Debug($"#{ClientSettings.ClientSession.SessionId}: Recieve the message {message} with id: {messageId}");

            output.Add(message);
        }
        public override void ChannelRead(IChannelHandlerContext ctx, object msg)
        {
            bool release = true;

            try
            {
                if (this.AcceptInboundMessage(msg))
                {
                    I imsg = (I)msg;
                    this.ChannelRead0(ctx, imsg);
                }
                else
                {
                    release = false;
                    ctx.FireChannelRead(msg);
                }
            }
            finally
            {
                if (autoRelease && release)
                {
                    ReferenceCountUtil.Release(msg);
                }
            }
        }
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            SafeProcess(() =>
            {
                var msg = (Message)message;
                if (msg.Type == MessageType.LoginResponse)
                {
                    DisposeCancellation();
                    _heartBeatCancellation = new CancellationTokenSource();
                    //得到登录响应后,开始心跳
                    context.Executor.ScheduleAsync(RunHeartBeat, context, _delay, _heartBeatCancellation.Token);
                }
                else if (msg.Type == MessageType.HeartBeatResponse)
                {
                    //得到回复后继续心跳
                    context.Executor.ScheduleAsync(RunHeartBeat, context, _delay, _heartBeatCancellation.Token);

                    ClientEvents.AsyncRaiseHeartBeatReceived(this.Client, this.Client.ServerEndPoint);
                }
                else
                {
                    context.FireChannelRead(message);
                }
            }, context);
        }
Example #17
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var buffer = (IByteBuffer)message;

            try
            {
                byte[] data = new byte[buffer.ReadableBytes];
                buffer.GetBytes(buffer.ReaderIndex, data);

                _logger.Debug($"received msg is: {Encoding.UTF8.GetString(data)}");
                var convertedMsg = JimuHelper.Deserialize <byte[], JimuTransportMsg>(data);
                if (convertedMsg.ContentType == typeof(JimuRemoteCallData).FullName)
                {
                    convertedMsg.Content = JimuHelper.Deserialize <string, JimuRemoteCallData>(convertedMsg.Content.ToString());
                }
                else if (convertedMsg.ContentType == typeof(JimuRemoteCallData).FullName)
                {
                    convertedMsg.Content = JimuHelper.Deserialize <string, JimuRemoteCallResultData>(convertedMsg.Content.ToString());
                }
                context.FireChannelRead(convertedMsg);
            }
            finally
            {
                buffer.Release();
            }
            //base.ChannelRead(context, message);
        }
        protected async void Decode(IChannelHandlerContext context, IByteBuffer message)
        {
            var buffer = message;

            while (buffer != null && buffer.ReadableBytes >= 4)
            {
                if (_readLength)
                {
                    var endianBuffer = buffer.WithOrder(ByteOrder.BigEndian);
                    _packetLength = endianBuffer.ReadInt();
                    _readLength   = false;
                }
                if (buffer.ReadableBytes >= _packetLength)
                {
                    var packet = buffer.ReadBytes(_packetLength).ToArray();
                    try
                    {
                        packet = Ionic.Zlib.ZlibStream.UncompressBuffer(packet);
                        var json = Encoding.UTF8.GetString(packet);
                        var data = JsonConvert.DeserializeObject(json);
                        foreach (var node in (JObject)data)
                        {
                            Type contentType;
                            var  converted = await _packetsConverter.ConvertAsync(node.Key, node.Value, out contentType);

                            if (contentType != null)
                            {
                                context.FireChannelRead(new Packet
                                {
                                    Bytes       = packet,
                                    CommandKey  = node.Key,
                                    Content     = converted,
                                    Data        = data,
                                    ContentType = contentType
                                });
                            }
                            else
                            {
#pragma warning disable 4014
                                context.WriteAndFlushAsync(new
                                {
                                    error = new
                                    {
                                        message = $"command not found: \"{node.Key}\""
                                    }
                                });
                            }
                        }
                        _readLength = true;
                    }
                    catch (Exception exception)
                    {
                        _logger.Error(exception);
                        context.CloseAsync();
                    }
                }
                break;
#pragma warning restore 4014
            }
        }
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var buffer = (IByteBuffer)message;

            try
            {
                byte[] data = new byte[buffer.ReadableBytes];
                buffer.GetBytes(buffer.ReaderIndex, data);

                if (data.Length < 102400)
                {
                    _logger.Debug($"recevied msg is: {Encoding.UTF8.GetString(data)}");
                }
                else
                {
                    _logger.Debug($"recevied msg is (bigger than 100k, we don't show it)");
                }
                var convertedMsg = JimuHelper.Deserialize <byte[], JimuTransportMsg>(data);
                context.FireChannelRead(convertedMsg);
                //context.FireChannelRead(data);
            }
            catch (Exception ex)
            {
                _logger.Debug($"Deserialize msg failure");
                context.WriteAndFlushAsync(Encoding.UTF8.GetBytes($"failure, {ex.ToStackTraceString()}"));
            }
            finally
            {
                buffer.Release();
            }
            //base.ChannelRead(context, message);
        }
Example #20
0
        /// <inheritdoc/>
        public override void ChannelRead(IChannelHandlerContext ctx, object msg)
        {
            if (!(msg is IFullHttpResponse response))
            {
                _ = ctx.FireChannelRead(msg);
                return;
            }

            try
            {
                if (!_handshaker.IsHandshakeComplete)
                {
                    _handshaker.FinishHandshake(ctx.Channel, response);
                    _ = _handshakePromise.TryComplete();
                    _ = ctx.FireUserEventTriggered(WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HandshakeComplete);
                    _ = ctx.Pipeline.Remove(this);
                    return;
                }

                ThrowHelper.ThrowInvalidOperationException_WebSocketClientHandshaker();
            }
            finally
            {
                _ = response.Release();
            }
        }
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     var buffer = (IByteBuffer)message;
     var data = buffer.ToArray();
     var transportMessage = _serializer.Deserialize<byte[], TransportMessage>(data);
     context.FireChannelRead(transportMessage);
 }
Example #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var msg = (Message)message;

            RequestManager requestManager = null;

            if (serviceResponseHandler != null)
            {
                var channelName = context.GetChannelName();
                requestManager = serviceResponseHandler(channelName);
            }

            //如果是服务响应消息,处理,其它消息透传
            if (msg.Header != null && msg.Header.Type == MessageType.SERVICE_RESP)
            {
                logger.LogDebug($"Get request result. Local={context.GetLocalNetString()}, Remote={context.GetRemoteNetString()}");
                if (requestManager != null)
                {
                    requestManager.CompleteRequest(msg.Header.RequestId, msg);
                }
            }
            else
            {
                context.FireChannelRead(message);
            }
        }
Example #23
0
        /// <summary>
        /// Any broadcast message which is handled by this handler has already been signature checked.
        /// The <see cref="BroadcastHandler"/> will get the original inner message and pass it onto the handler
        /// in-charge of executing the RX handlers.
        /// </summary>
        /// <param name="ctx">The Channel handler context.</param>
        /// <param name="msg">The gossip message.</param>
        protected override void ChannelRead0(IChannelHandlerContext ctx, ProtocolMessage msg)
        {
            if (msg.IsBroadCastMessage())
            {
                Logger.Verbose("Broadcast message {msg} received.", msg);
                var innerGossipMessageSigned = ProtocolMessage.Parser.ParseFrom(msg.Value);
                _broadcastManager.ReceiveAsync(innerGossipMessageSigned)
                .ConfigureAwait(false).GetAwaiter().GetResult();

                ctx.FireChannelRead(innerGossipMessageSigned);
                return;
            }

            Logger.Verbose("Message {msg} was not a broadcast message.", msg);
            ctx.FireChannelRead(msg);
        }
Example #24
0
        public override void ChannelRead(IChannelHandlerContext ctx, object msg)
        {
            if (!(msg is IFullHttpResponse))
            {
                ctx.FireChannelRead(msg);
                return;
            }

            var response = (IFullHttpResponse)msg;

            try
            {
                if (!this.handshaker.IsHandshakeComplete)
                {
                    this.handshaker.FinishHandshake(ctx.Channel, response);
                    ctx.FireUserEventTriggered(WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HandshakeComplete);
                    ctx.Channel.Pipeline.Remove(this);
                    return;
                }

                throw new InvalidOperationException("WebSocketClientHandshaker should have been non finished yet");
            }
            finally
            {
                response.Release();
            }
        }
Example #25
0
 protected static void FireChannelRead(IChannelHandlerContext ctx, List <object> output, int numElements)
 {
     for (int i = 0; i < numElements; i++)
     {
         _ = ctx.FireChannelRead(output[i]);
     }
 }
        /**
         * Dequeues one or many (or none) messages depending on the channel's auto
         * reading state and returns the number of messages that were consumed from
         * the internal queue.
         *
         * The {@code minConsume} argument is used to force {@code dequeue()} into
         * consuming that number of messages regardless of the channel's auto
         * reading configuration.
         *
         * @see #read(ChannelHandlerContext)
         * @see #channelRead(ChannelHandlerContext, Object)
         */
        int Dequeue(IChannelHandlerContext ctx, int minConsume)
        {
            if (this.queue != null)
            {
                int consumed = 0;

                while ((consumed < minConsume || this.config.AutoRead) && this.queue.TryDequeue(out object msg))
                {
                    ++consumed;
                    ctx.FireChannelRead(msg);
                }

                // We're firing a completion event every time one (or more)
                // messages were consumed and the queue ended up being drained
                // to an empty state.
                if (this.queue.IsEmpty && consumed > 0)
                {
                    ctx.FireChannelReadComplete();
                }

                return(consumed);
            }

            return(0);
        }
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     if (_finished)
     {
         // Received a message after the connection has been established; pass through.
         _suppressChannelReadComplete = false;
         _ctx.FireChannelRead(message);
     }
     else
     {
         _suppressChannelReadComplete = true;
         Exception cause = null;
         try
         {
             var done = HandleResponse(_ctx, message);
             if (done)
             {
                 SetConnectSuccess();
             }
         }
         catch (Exception t)
         {
             cause = t;
         }
         finally
         {
             ReferenceCountUtil.Release(message);
             if (cause != null)
             {
                 SetConnectFailure(cause);
             }
         }
     }
 }
Example #28
0
        public void RmiMessage(IChannelHandlerContext context, RmiMessage message, RecvContext recvContext)
        {
            var buffer = Unpooled.WrappedBuffer(message.Data);

            recvContext.Message = buffer;
            context.FireChannelRead(recvContext);
        }
Example #29
0
        /// <inheritdoc />
        public override void HandlerRemoved(IChannelHandlerContext context)
        {
            if (_decodeState == STATE_CALLING_CHILD_DECODE)
            {
                _decodeState = STATE_HANDLER_REMOVED_PENDING;
                return;
            }
            IByteBuffer buf = _cumulation;

            if (buf is object)
            {
                // Directly set this to null so we are sure we not access it in any other method here anymore.
                _cumulation = null;
                _numReads   = 0;
                int readable = buf.ReadableBytes;
                if (readable > 0)
                {
                    _ = context.FireChannelRead(buf);
                    _ = context.FireChannelReadComplete();
                }
                else
                {
                    _ = buf.Release();
                }
            }
            HandlerRemovedInternal(context);
        }
 public override void ChannelRead(IChannelHandlerContext context, object msg)
 {
     if (finished)
     {
         // Received a message after the connection has been established; pass through.
         suppressChannelReadComplete = false;
         context.FireChannelRead(msg);
     }
     else
     {
         suppressChannelReadComplete = true;
         Exception cause = null;
         try
         {
             bool done = handleResponse(context, msg);
             if (done)
             {
                 setConnectSuccess(context);
             }
         }
         catch (Exception t)
         {
             cause = t;
         }
         finally
         {
             ReferenceCountUtil.Release(msg);
             if (cause != null)
             {
                 ctx_c          = context;
                 ConnectFailure = cause;
             }
         }
     }
 }
 private static void FireChannelRead(IChannelHandlerContext context, List <object> msgs, int numElements)
 {
     for (var i = 0; i < numElements; i++)
     {
         context.FireChannelRead(msgs[i]);
     }
 }
Example #32
0
        /**
         * Dequeues one or many (or none) messages depending on the channel's auto
         * reading state and returns the number of messages that were consumed from
         * the internal queue.
         *
         * The {@code minConsume} argument is used to force {@code dequeue()} into
         * consuming that number of messages regardless of the channel's auto
         * reading configuration.
         *
         * @see #read(ChannelHandlerContext)
         * @see #channelRead(ChannelHandlerContext, Object)
         */
        private int Dequeue(IChannelHandlerContext ctx, int minConsume)
        {
            int consumed = 0;

            // fireChannelRead(...) may call ctx.read() and so this method may reentrance. Because of this we need to
            // check if queue was set to null in the meantime and if so break the loop.
            while (_queue is object && (consumed < minConsume || _config.IsAutoRead))
            {
                if (!_queue.TryDequeue(out object msg) || msg is null)
                {
                    break;
                }

                ++consumed;
                _ = ctx.FireChannelRead(msg);
            }

            // We're firing a completion event every time one (or more)
            // messages were consumed and the queue ended up being drained
            // to an empty state.
            if (_queue is object && _queue.IsEmpty)
            {
                _queue.Recycle();
                _queue = null;

                if (consumed > 0)
                {
                    _ = ctx.FireChannelReadComplete();
                }
            }

            return(consumed);
        }
Example #33
0
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     if (++_actualReads == _expectedReads)
     {
         _signal.Signal();
     }
     context.FireChannelRead(message);
 }
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     var packet = message as PublishPacket;
     if (packet != null)
     {
         IByteBuffer result = ApplyCompression(packet.Payload, CompressionMode.Decompress);
         packet.Payload = result;
     }
     context.FireChannelRead(message);
 }
Example #35
0
 public override void HandlerRemoved(IChannelHandlerContext context)
 {
     var buf = InternalBuffer;
     var readable = buf.ReadableBytes;
     if (readable > 0)
     {
         var bytes = buf.ReadBytes(readable);
         buf.Release();
         context.FireChannelRead(bytes);
     }
     else
     {
         buf.Release();
     }
     _cumulation = null;
     _numReads = 0;
     context.FireChannelReadComplete();
     HandlerRemovedInternal(context);
 }
 public override void ChannelInactive(IChannelHandlerContext ctx)
 {
     ThreadLocalObjectList output = ThreadLocalObjectList.Take();
     try
     {
         if (this.cumulation != null)
         {
             this.CallDecode(ctx, this.cumulation, output);
             this.DecodeLast(ctx, this.cumulation, output);
         }
         else
         {
             this.DecodeLast(ctx, Unpooled.Empty, output);
         }
     }
     catch (DecoderException e)
     {
         throw e;
     }
     catch (Exception e)
     {
         throw new DecoderException(e);
     }
     finally
     {
         try
         {
             if (this.cumulation != null)
             {
                 this.cumulation.Release();
                 this.cumulation = null;
             }
             int size = output.Count;
             for (int i = 0; i < size; i++)
             {
                 ctx.FireChannelRead(output[i]);
             }
             if (size > 0)
             {
                 // Something was read, call fireChannelReadComplete()
                 ctx.FireChannelReadComplete();
             }
             ctx.FireChannelInactive();
         }
         finally
         {
             // recycle in all cases
             output.Return();
         }
     }
 }
 public virtual void ChannelRead(IChannelHandlerContext context, object message) => context.FireChannelRead(message);
 public override void HandlerRemoved(IChannelHandlerContext context)
 {
     IByteBuffer buf = this.InternalBuffer;
     int readable = buf.ReadableBytes;
     if (readable > 0)
     {
         IByteBuffer bytes = buf.ReadBytes(readable);
         buf.Release();
         context.FireChannelRead(bytes);
     }
     else
     {
         buf.Release();
     }
     this.cumulation = null;
     context.FireChannelReadComplete();
     this.HandlerRemovedInternal(context);
 }
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var data = message as IByteBuffer;
            if (data != null)
            {
                ThreadLocalObjectList output = ThreadLocalObjectList.Take();
                try
                {
                    this.first = this.cumulation == null;
                    if (this.first)
                    {
                        this.cumulation = data;
                    }
                    else
                    {
                        this.cumulation = this.cumulator(context.Allocator, this.cumulation, data);
                    }
                    this.CallDecode(context, this.cumulation, output);
                }
                catch (DecoderException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw new DecoderException(ex);
                }
                finally
                {
                    if (this.cumulation != null && !this.cumulation.IsReadable())
                    {
                        this.cumulation.Release();
                        this.cumulation = null;
                    }
                    int size = output.Count;
                    this.decodeWasNull = size == 0;

                    for (int i = 0; i < size; i++)
                    {
                        context.FireChannelRead(output[i]);
                    }
                    output.Return();
                }
            }
            else
            {
                context.FireChannelRead(message);
            }
        }
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     if (message == _upgradeMessage)
     {
         context.Pipeline.Remove(_decoder);
         return;
     }
     context.FireChannelRead(message);
 }
Example #41
0
 private static void FireChannelRead(IChannelHandlerContext context, List<object> msgs, int numElements)
 {
     for (var i = 0; i < numElements; i++)
         context.FireChannelRead(msgs[i]);
 }
Example #42
0
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     context.FireChannelRead(first);
     context.FireChannelRead(second);
 }
Example #43
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            if (this.readerIdleTime.Ticks > 0 || this.allIdleTime.Ticks > 0)
            {
                this.reading = true;
                this.firstReaderIdleEvent = this.firstAllIdleEvent = true;
            }

            context.FireChannelRead(message);
        }
Example #44
0
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     if (++_actualReadCount == _expectedReadCount)
         _resetEvent.Set();
     context.FireChannelRead(message);
 }
Example #45
0
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     this.reading = true;
     context.FireChannelRead(message);
 }
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     this.throughput.Increment();
     context.FireChannelRead(message);
 }
Example #47
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            if (message is IByteBuf)
            {
                var output = RecyclableArrayList.Take();
                try
                {
                    var data = (IByteBuf) message;
                    _first = _cumulation == null;
                    if (_first)
                    {
                        _cumulation = data;
                    }
                    else
                    {
                        _cumulation = _cumulator(context.Allocator, _cumulation, data);
                    }
                    CallDecode(context, _cumulation, output);
                }
                catch (DecoderException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw new DecoderException(ex);
                }
                finally
                {
                    if (_cumulation != null && !_cumulation.IsReadable())
                    {
                        _numReads = 0;
                        _cumulation.Release();
                        _cumulation = null;
                    }
                    else if (++_numReads >= _discardAfterReads)
                    {
                        _numReads = 0;
                        DiscardSomeReadBytes();
                    }

                    var size = output.Count;
                    _decodeWasNull = size == 0;
                    FireChannelRead(context, output, size);
                    output.Return();
                }
            }
            else
            {
                // not a byte buffer? then we can't handle it. Forward it along 
                context.FireChannelRead(message);
            }
        }
Example #48
0
 public override void ChannelRead(IChannelHandlerContext ctx, object message)
 {
     if (this.Logger.IsEnabled(this.InternalLevel))
     {
         this.Logger.Log(this.InternalLevel, this.Format(ctx, "RECEIVED", message));
     }
     ctx.FireChannelRead(message);
 }
Example #49
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            if (message is IByteBuf)
            {
                ReadInstruction mode;
                var buf = (IByteBuf) message;
                mode = _instructions.Any() && buf.ReadableBytes > 4 ? _instructions.Dequeue() : ReadInstruction.Full;

                if (mode.Mode == ReadMode.Full)
                {
                    var writeBuf =
                        context.Allocator.Buffer(_cumulativeBuffer.ReadableBytes + buf.ReadableBytes)
                            .WriteBytes(_cumulativeBuffer)
                            .WriteBytes(buf);
                    Assert.Equal(0, _cumulativeBuffer.ReadableBytes);
                    // verify that we've fully drained the cumulative buffer
                    _cumulativeBuffer.DiscardReadBytes();
                    context.FireChannelRead(writeBuf);
                }
                else
                {
                    var originalBytes = buf.ReadableBytes;
                    var partialReadBytes = mode.ReadBytes;
                    var writeBuf =
                        context.Allocator.Buffer(_cumulativeBuffer.ReadableBytes + partialReadBytes)
                            .WriteBytes(_cumulativeBuffer)
                            .WriteBytes(buf, partialReadBytes);
                    Assert.Equal(0, _cumulativeBuffer.ReadableBytes);
                    // verify that we've fully drained the cumulative buffer
                    _cumulativeBuffer.DiscardReadBytes();

                    // store the rest partial read into the cumulative buffer
                    _cumulativeBuffer.WriteBytes(buf, partialReadBytes, buf.ReadableBytes);
                    Assert.Equal(partialReadBytes + _cumulativeBuffer.ReadableBytes, originalBytes);

                    context.FireChannelRead(writeBuf);
                }
            }
            else
            {
                // move onto the next handler if this message is not an IByteBuf
                context.FireChannelRead(message);
            }
        }
Example #50
0
 public override void UserEventTriggered(IChannelHandlerContext context, object evt)
 {
     if (evt is FinishPartialReads)
     {
         if (_cumulativeBuffer.IsReadable())
         {
             var writeBuf =
                 context.Allocator.Buffer(_cumulativeBuffer.ReadableBytes)
                     .WriteBytes(_cumulativeBuffer);
             context.FireChannelRead(writeBuf);
         }
     }
 }