public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var buffer = message as IByteBuffer;
            if (buffer != null)
            {
                int stringLength = buffer.ReadByte();
                var b = new byte[stringLength];
                buffer.ReadBytes(b, 0, b.Length);
                string instanceId = Encoding.UTF8.GetString(b);

                stringLength = buffer.ReadByte();
                b = new byte[stringLength];
                buffer.ReadBytes(b, 0, b.Length);
                string messageType = Encoding.UTF8.GetString(b);

                this.parent.SetInstanceIdChannel(instanceId, context.Channel);

                if (!this.clientConnectedInvoked)
                {
                    this.clientConnectedAction?.Invoke(instanceId, context.Channel.Id.AsShortText());
                    this.clientConnectedInvoked = true;
                }

                Task.Run(() =>
                {
                    this.dataReceivedAction(instanceId, context.Channel.Id.AsShortText(), messageType, buffer.ToArray());
                });
            }
        }
        //---------------------------------------------------------------------
        public async void ChannelActive(IChannelHandlerContext context)
        {
            this.context = context;
            listener.GatewaySession = this;

            await this.listener.OnSessionCreate();
        }
        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            if (!(exception is ObjectDisposedException))
                log.Warn($"Exception in NettyServerHandler {context.Channel.Id.AsShortText()}: {exception.Message}");

            context.CloseAsync();
        }
        //---------------------------------------------------------------------
        public override void ChannelActive(IChannelHandlerContext context)
        {
            var session = (GatewaySession)this.factory.createRpcSession(null);
            mapSession[context] = session;

            session.ChannelActive(context);
        }
Example #5
0
        /// <summary>
        /// Process data that was received from the channel.
        /// </summary>
        /// <param name="ctx">Context which is used for the currently processed channel</param>
        /// <param name="e">Event being processed.</param>
        public void HandleUpstream(IChannelHandlerContext ctx, IChannelEvent e)
        {
            if (e is ConnectedEvent)
            {
                ctx.State = new Context();
            }
            if (e is ClosedEvent)
            {
                Reset();
            }
            else if (e is MessageEvent)
            {
                _context = ctx.State.As<Context>();
                _context._buffer = e.As<MessageEvent>().Message.As<BufferSlice>();
                _context._reader.Assign(_context._buffer);
                while (_context._parserMethod()) ;

                if (_context._isComplete)
                {
                    e.As<MessageEvent>().Message = _context._message;
                    OnComplete(ctx, e);
                }
                return;
            }

            ctx.SendUpstream(e);
        }
 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 #7
0
        protected override void HandleMessage(IChannelHandlerContext ctx, MessageEvent e)
        {
            var msg = (Message) e.Message;
            string contentType = msg.Headers["Content-Type"];

            var reader = new StreamReader(msg.Body);
            string body = reader.ReadToEnd();
            msg.Body.Position = 0;

            switch (contentType)
            {
                case "auth/request":
                    SendCommand("auth", _password);
                    break;
                case "command/reply":
                    {
                        Command cmd;
                        if (!_commands.TryPop(out cmd))
                            throw new InvalidOperationException(
                                "Failed to find a command for the recieved command/reply");
                        OnCommand(cmd, msg);
                    }

                    break;
                case "text/event-plain":
                    ParseEvent(msg.Body);
                    break;
                default:
                    break;
            }
        }
Example #8
0
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     if (++_actualReads == _expectedReads)
     {
         _signal.Signal();
     }
     context.FireChannelRead(message);
 }
        public override void ChannelActive(IChannelHandlerContext context)
        {
            log.Info($"Channel {context.Channel.Id.AsShortText()} connected");

            this.clientConnectedInvoked = false;

            base.ChannelActive(context);
        }
Example #10
0
 public override void ChannelInactive(IChannelHandlerContext context)
 {
     if (!WrappedTransport.ConnectionGroup.TryRemove(context.Channel))
     {
         Log.Warning("Unable to ADD channel [{0}->{1}](Id={2}) to connection group. May not shut down cleanly.",
             context.Channel.LocalAddress, context.Channel.RemoteAddress, context.Channel.Id);
     }
 }
Example #11
0
        public PendingWriteQueue(IChannelHandlerContext ctx)
        {
            Contract.Requires(ctx != null);

            this.ctx = ctx;
            this.buffer = ctx.Channel.Unsafe.OutboundBuffer;
            this.estimatorHandle = ctx.Channel.Configuration.MessageSizeEstimator.NewHandle();
        }
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     if (message is int)
     {
         State = State.ReceiveMessages((int) message);
         Logger.Debug("[Client-Read] Received: {0}", message);
     }
 }
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     ReferenceCountUtil.Release(message);
     if (++this.actualReads == this.expectedReads)
     {
         this.signal.Signal();
     }
 }
 protected internal sealed override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
 {
     object decode = this.Decode(context, input);
     if (decode != null)
     {
         output.Add(decode);
     }
 }
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     Received.Add((IByteBuf) message);
     if (++_actualReadCount == _expectedReadCount)
     {
         _readFinished.Set();
     }
 }
 public override Task WriteAsync(IChannelHandlerContext context, object message)
 {
     if (message is int)
     {
         State = State.WriteMessages((int) message);
     }
     return base.WriteAsync(context, message);
 }
Example #17
0
 /// <summary>
 /// Handle the data that is going to be sent to the remote end point
 /// </summary>
 /// <param name="ctx">Context information</param>
 /// <param name="e">Chennel event.</param>
 public void HandleDownstream(IChannelHandlerContext ctx, IChannelEvent e)
 {
     if (e is CloseEvent && _timer != null)
     {
         _timer.Dispose();
         _timer = null;
     }
 }
Example #18
0
 public override Task WriteAsync(IChannelHandlerContext context, object message)
 {
     if (message is int)
     {
         var buf = Unpooled.Buffer(4).WriteInt((int) message);
         return context.WriteAsync(buf);
     }
     return context.WriteAsync(message);
 }
 public override Task WriteAsync(IChannelHandlerContext context, object message)
 {
     if (message is int)
     {
         State = State.WriteMessages((int) message);
         Logger.Debug("[Client-Write] Writing: {0}", message);
     }
     return context.WriteAsync(message);
 }
 protected override void Encode(IChannelHandlerContext context, IByteBuf message, List<object> output)
 {
     base.Encode(context, message, _temporaryOutput);
     var lengthFrame = (IByteBuf) _temporaryOutput[0];
     var combined = lengthFrame.WriteBytes(message);
     ReferenceCountUtil.SafeRelease(message, 1); // ready to release it - bytes have been copied
     output.Add(combined.Retain());
     _temporaryOutput.Clear();
 }
Example #21
0
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     var buffer = message as IByteBuffer;
     if (buffer != null)
     {
         Console.WriteLine("Received from client: " + buffer.ToString(Encoding.UTF8));
     }
     context.WriteAsync(message);
 }
Example #22
0
        //---------------------------------------------------------------------
        public override void ChannelActive(IChannelHandlerContext context)
        {
            //context.WriteAndFlushAsync(this.initialMessage);

            var session = (ClientSession)this.factory.createRpcSession(null);
            mapSession[context] = session;

            session.ChannelActive(context);
        }
 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);
 }
 public override Task WriteAsync(IChannelHandlerContext context, object message)
 {
     var packet = message as PublishPacket;
     if (packet != null)
     {
         IByteBuffer result = ApplyCompression(packet.Payload, CompressionMode.Compress);
         packet.Payload = result;
     }
     return context.WriteAsync(message);
 }
        //---------------------------------------------------------------------
        public override void ChannelInactive(IChannelHandlerContext context)
        {
            GatewaySession session = null;
            mapSession.TryRemove(context, out session);

            if (session != null)
            {
                session.ChannelInactive(context);
            }
        }
 public override void ChannelRead(IChannelHandlerContext context, object message)
 {
     CancellationTokenSource cts = this.responseTimeoutCts;
     if (cts != null)
     {
         cts.Cancel();
     }
     this.lastReceivedMessage = message;
     this.ContinueScenarioExecution(context);
 }
        void ExecuteStep(IChannelHandlerContext context, TestScenarioStep currentStep)
        {
            if (!context.Channel.Open)
            {
                // todo: dispose scheduled work in case of channel closure instead?
                return;
            }

            Task lastTask = null;
            object lastMessage = null;
            foreach (object message in currentStep.Messages)
            {
                lastMessage = message;
                var writeTimeoutCts = new CancellationTokenSource();
                Task task = context.WriteAsync(message);
                object timeoutExcMessage = message;
                context.Channel.EventLoop.ScheduleAsync(
                    () => this.completion.TrySetException(new TimeoutException(string.Format("Sending of message did not complete in time: {0}", timeoutExcMessage))),
                    this.sendTimeout,
                    writeTimeoutCts.Token);
                task.ContinueWith(
                    t => writeTimeoutCts.Cancel(),
                    TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
                task.OnFault(t => this.completion.TrySetException(t.Exception));

                lastTask = task;
            }

            if (currentStep.WaitForFeedback)
            {
                if (this.responseTimeout > TimeSpan.Zero)
                {
                    this.responseTimeoutCts = new CancellationTokenSource();
                    if (lastTask == null)
                    {
                        this.ScheduleReadTimeoutCheck(context, null);
                    }
                    else
                    {
                        lastTask.ContinueWith(
                            t => this.ScheduleReadTimeoutCheck(context, lastMessage),
                            TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
                    }
                }
            }

            context.Flush();

            if (!currentStep.WaitForFeedback)
            {
                context.Channel.EventLoop.Execute(
                    ctx => this.ContinueScenarioExecution((IChannelHandlerContext)ctx),
                    context);
            }
        }
 public static void InvokeChannelUnregisteredNow(IChannelHandlerContext ctx)
 {
     try
     {
         ctx.Handler.ChannelUnregistered(ctx);
     }
     catch (Exception ex)
     {
         NotifyHandlerException(ctx, ex);
     }
 }
 public static void InvokeUserEventTriggeredNow(IChannelHandlerContext ctx, object evt)
 {
     try
     {
         ctx.Handler.UserEventTriggered(ctx, evt);
     }
     catch (Exception ex)
     {
         NotifyHandlerException(ctx, ex);
     }
 }
 public static void InvokeChannelInactiveNow(IChannelHandlerContext ctx)
 {
     try
     {
         ctx.Handler.ChannelInactive(ctx);
     }
     catch (Exception ex)
     {
         NotifyHandlerException(ctx, ex);
     }
 }
Example #31
0
 public override void ChannelInactive(IChannelHandlerContext context)
 {
     ChannelInputClosed(context, true);
 }
Example #32
0
 public override void ChannelInactive(IChannelHandlerContext context)
 {
     this.CleanupSafely(context);
     base.ChannelInactive(context);
 }
Example #33
0
 public void Decoder(IChannelHandlerContext ctx, IByteBuf buf, List <object> output)
 {
     this.Decode(ctx, buf, output);
 }
Example #34
0
 public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
 {
     //客户端主动断开需要应答,否则socket变成CLOSE_WAIT状态导致socket资源耗尽
     context.CloseAsync();
     _logger.LogError(exception, $"与服务器:{context.Channel.RemoteAddress}通信时发送了错误。");
 }
Example #35
0
 public override void ChannelInactive(IChannelHandlerContext context)
 {
     Logger.Log.Warn(string.Format(LogLanguage.Instance.GetMessageFromKey(LanguageKey.UNREGISTRED_FROM_MASTER)));
     Task.Run(() => _onConnectionLost());
 }
Example #36
0
 protected virtual void HandlerRemovedInternal(IChannelHandlerContext context)
 {
 }
Example #37
0
 internal static Task SendAsync(IChannelHandlerContext context, SmsPacket packet)
 {
     return(SendAsync(context.Channel, packet));
 }
Example #38
0
 public override void ChannelActive(IChannelHandlerContext context)
 {
     _logger.Information(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.CLIENT_CONNECTED),
                         ClientId);
 }
Example #39
0
 public override void ChannelInactive(IChannelHandlerContext context)
 {
     NotifyListener(new Disassociated(DisassociateInfo.Unknown));
     base.ChannelInactive(context);
 }
Example #40
0
 public override void ChannelActive(IChannelHandlerContext context)
 {
     InitOutbound(context.Channel, (IPEndPoint)context.Channel.RemoteAddress, null);
     base.ChannelActive(context);
 }
 public ClientContext(IChannelHandlerContext context)
 {
     Context = context;
 }
Example #42
0
 public override void ChannelRegistered(IChannelHandlerContext context)
 {
     _context = context;
 }
Example #43
0
        protected override async void ChannelRead0(IChannelHandlerContext ctx, Packet msg)
        {
            try
            {
                _context = ctx; // Save context for manual Ping later
                switch (msg.PacketType)
                {
                case PacketType.CONNACK:
                    Debug.WriteLine($"{nameof(PushClient)}:\tCONNACK received.");
                    ConnectionData.UpdateAuth(((FbnsConnAckPacket)msg).Authentication);
                    RegisterMqttClient(ctx);
                    break;

                case PacketType.PUBLISH:
                    Debug.WriteLine($"{nameof(PushClient)}:\tPUBLISH received.");
                    var publishPacket = (PublishPacket)msg;
                    if (publishPacket.QualityOfService == QualityOfService.AtLeastOnce)
                    {
                        await ctx.WriteAndFlushAsync(PubAckPacket.InResponseTo(publishPacket));
                    }

                    var payload = DecompressPayload(publishPacket.Payload);
                    var json    = Encoding.UTF8.GetString(payload);
                    Debug.WriteLine($"{nameof(PushClient)}:\tMQTT json: {json}");
                    switch (Enum.Parse(typeof(TopicIds), publishPacket.TopicName))
                    {
                    case TopicIds.Message:
                        var message = JsonConvert.DeserializeObject <PushReceivedEventArgs>(json);
                        message.Json = json;
                        OnMessageReceived(message);
                        break;

                    case TopicIds.RegResp:
                        OnRegisterResponse(json);
                        try
                        {
                            await _context.Executor.Schedule(KeepAliveLoop,
                                                             TimeSpan.FromSeconds(KEEP_ALIVE - 60));
                        }
                        catch (TaskCanceledException)
                        {
                            // pass
                        }

                        break;

                    default:
                        Debug.WriteLine($"Unknown topic received: {publishPacket.TopicName}", "Warning");
                        break;
                    }

                    break;

                case PacketType.PUBACK:
                    Debug.WriteLine($"{nameof(PushClient)}:\tPUBACK received.");
                    _waitingForPubAck = false;
                    break;

                // todo: PingResp never arrives even though data was received. Decoder problem?
                case PacketType.PINGRESP:
                    Debug.WriteLine($"{nameof(PushClient)}:\tPINGRESP received.");
                    break;

                default:
                    throw new NotSupportedException($"Packet type {msg.PacketType} is not supported.");
                }
            }
            catch (Exception e)
            {
                // Something went wrong with Push client. Shutting down.
#if !DEBUG
                Crashes.TrackError(e);
#endif
                await Shutdown().ConfigureAwait(false);
            }
        }
 public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
 {
     this.output.WriteLine(string.Format("Exception: {0}", exception));
     base.ExceptionCaught(context, exception);
 }
 public override void UserEventTriggered(IChannelHandlerContext context, object evt)
 {
     this.output.WriteLine(string.Format("User Event: {0}", evt));
     base.UserEventTriggered(context, evt);
 }
Example #46
0
 public override void HandlerRemoved(IChannelHandlerContext context)
 {
     this.CleanupSafely(context);
     base.HandlerRemoved(context);
 }
 /// <seealso cref= CommandDecoder#decode(io.netty.channel.IChannelHandlerContext, io.netty.buffer.IByteBuffer, java.util.List<object>) </seealso>
 //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
 //ORIGINAL LINE: @Override public void decode(io.netty.channel.IChannelHandlerContext ctx, io.netty.buffer.IByteBuffer in, java.util.List<object><Object> out) throws Exception
 public virtual void decode(IChannelHandlerContext ctx, IByteBuffer @in, List <object> @out)
 {
     // the less length between response header and request header
     if (@in.ReadableBytes >= lessLen)
     {
         @in.MarkReaderIndex();
         byte protocol = @in.ReadByte();
         @in.ResetReaderIndex();
         if (protocol == RpcProtocol.PROTOCOL_CODE)
         {
             /*
              * ver: version for protocol
              * type: request/response/request oneway
              * cmdcode: code for remoting command
              * ver2:version for remoting command
              * requestId: id of request
              * codec: code for codec
              * (req)timeout: request timeout
              * (resp)respStatus: response status
              * classLen: length of request or response class name
              * headerLen: length of header
              * contentLen: length of content
              * className
              * header
              * content
              */
             if (@in.ReadableBytes > 2)
             {
                 @in.MarkReaderIndex();
                 @in.ReadByte();             //version
                 byte type = @in.ReadByte(); //type
                 if (type == RpcCommandType.REQUEST || type == RpcCommandType.REQUEST_ONEWAY)
                 {
                     //decode request
                     if (@in.ReadableBytes >= RpcProtocol.RequestHeaderLength - 2)
                     {
                         short  cmdCode    = @in.ReadShort();
                         byte   ver2       = @in.ReadByte();
                         int    requestId  = @in.ReadInt();
                         byte   serializer = @in.ReadByte();
                         int    timeout    = @in.ReadInt();
                         short  classLen   = @in.ReadShort();
                         short  headerLen  = @in.ReadShort();
                         int    contentLen = @in.ReadInt();
                         byte[] clazz      = null;
                         byte[] header     = null;
                         byte[] content    = null;
                         if (@in.ReadableBytes >= classLen + headerLen + contentLen)
                         {
                             if (classLen > 0)
                             {
                                 clazz = new byte[classLen];
                                 @in.ReadBytes(clazz);
                             }
                             if (headerLen > 0)
                             {
                                 header = new byte[headerLen];
                                 @in.ReadBytes(header);
                             }
                             if (contentLen > 0)
                             {
                                 content = new byte[contentLen];
                                 @in.ReadBytes(content);
                             }
                         }
                         else
                         { // not enough data
                             @in.ResetReaderIndex();
                             return;
                         }
                         RequestCommand command;
                         if (cmdCode == (short)CommonCommandCode.__Enum.HEARTBEAT)
                         {
                             command = new HeartbeatCommand();
                         }
                         else
                         {
                             command = createRequestCommand(cmdCode);
                         }
                         command.Type       = type;
                         command.Version    = ver2;
                         command.Id         = requestId;
                         command.Serializer = serializer;
                         command.Timeout    = timeout;
                         command.Clazz      = clazz;
                         command.Header     = header;
                         command.Content    = content;
                         @out.Add(command);
                     }
                     else
                     {
                         @in.ResetReaderIndex();
                     }
                 }
                 else if (type == RpcCommandType.RESPONSE)
                 {
                     //decode response
                     if (@in.ReadableBytes >= RpcProtocol.ResponseHeaderLength - 2)
                     {
                         short  cmdCode    = @in.ReadShort();
                         byte   ver2       = @in.ReadByte();
                         int    requestId  = @in.ReadInt();
                         byte   serializer = @in.ReadByte();
                         short  status     = @in.ReadShort();
                         short  classLen   = @in.ReadShort();
                         short  headerLen  = @in.ReadShort();
                         int    contentLen = @in.ReadInt();
                         byte[] clazz      = null;
                         byte[] header     = null;
                         byte[] content    = null;
                         if (@in.ReadableBytes >= classLen + headerLen + contentLen)
                         {
                             if (classLen > 0)
                             {
                                 clazz = new byte[classLen];
                                 @in.ReadBytes(clazz);
                             }
                             if (headerLen > 0)
                             {
                                 header = new byte[headerLen];
                                 @in.ReadBytes(header);
                             }
                             if (contentLen > 0)
                             {
                                 content = new byte[contentLen];
                                 @in.ReadBytes(content);
                             }
                         }
                         else
                         { // not enough data
                             @in.ResetReaderIndex();
                             return;
                         }
                         ResponseCommand command;
                         if (cmdCode == (short)CommonCommandCode.__Enum.HEARTBEAT)
                         {
                             command = new HeartbeatAckCommand();
                         }
                         else
                         {
                             command = createResponseCommand(cmdCode);
                         }
                         command.Type               = type;
                         command.Version            = ver2;
                         command.Id                 = requestId;
                         command.Serializer         = serializer;
                         command.ResponseStatus     = (ResponseStatus)status;
                         command.Clazz              = clazz;
                         command.Header             = header;
                         command.Content            = content;
                         command.ResponseTimeMillis = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
                         command.ResponseHost       = (IPEndPoint)ctx.Channel.RemoteAddress;
                         @out.Add(command);
                     }
                     else
                     {
                         @in.ResetReaderIndex();
                     }
                 }
                 else
                 {
                     string emsg = "Unknown command type: " + type;
                     logger.LogError(emsg);
                     throw new Exception(emsg);
                 }
             }
         }
         else
         {
             string emsg = "Unknown protocol: " + protocol;
             logger.LogError(emsg);
             throw new Exception(emsg);
         }
     }
 }
 public void Init(IPacketSender packetSender, IChannelHandlerContext context)
 {
     _session.Init(5, context, packetSender);
 }
Example #49
0
 public override void ChannelActive(IChannelHandlerContext context)
 {
     Logger.Log.Debug(string.Format(LogLanguage.Instance.GetMessageFromKey(LanguageKey.REGISTRED_ON_MASTER)));
 }
Example #50
0
        protected override void Decode(IChannelHandlerContext context, IHttpObject message, List <object> output)
        {
            try
            {
                if (message is IHttpResponse response && response.Status.Code == StatusCodes.Status100Continue)
                {
                    if (!(response is ILastHttpContent))
                    {
                        this.continueResponse = true;
                    }
                    // 100-continue response must be passed through.
                    output.Add(ReferenceCountUtil.Retain(message));
                    return;
                }

                if (this.continueResponse)
                {
                    if (message is ILastHttpContent)
                    {
                        this.continueResponse = false;
                    }
                    // 100-continue response must be passed through.
                    output.Add(ReferenceCountUtil.Retain(message));
                    return;
                }

                var httpContent = message as IHttpContent;
                if (message is IHttpMessage httpMessage)
                {
                    this.Cleanup();
                    HttpHeaders headers = httpMessage.Headers;

                    // Determine the content encoding.
                    if (headers.TryGet(HttpHeaderNames.ContentEncoding, out ICharSequence contentEncoding))
                    {
                        contentEncoding = AsciiString.Trim(contentEncoding);
                    }
                    else
                    {
                        contentEncoding = Identity;
                    }
                    this.decoder = this.NewContentDecoder(contentEncoding);

                    if (this.decoder is null)
                    {
                        if (httpContent is object)
                        {
                            _ = httpContent.Retain();
                        }
                        output.Add(httpMessage);
                        return;
                    }

                    // Remove content-length header:
                    // the correct value can be set only after all chunks are processed/decoded.
                    // If buffering is not an issue, add HttpObjectAggregator down the chain, it will set the header.
                    // Otherwise, rely on LastHttpContent message.
                    if (headers.Contains(HttpHeaderNames.ContentLength))
                    {
                        _ = headers.Remove(HttpHeaderNames.ContentLength);
                        _ = headers.Set(HttpHeaderNames.TransferEncoding, HttpHeaderValues.Chunked);
                    }
                    // Either it is already chunked or EOF terminated.
                    // See https://github.com/netty/netty/issues/5892

                    // set new content encoding,
                    ICharSequence targetContentEncoding = this.GetTargetContentEncoding(contentEncoding);
                    if (HttpHeaderValues.Identity.ContentEquals(targetContentEncoding))
                    {
                        // Do NOT set the 'Content-Encoding' header if the target encoding is 'identity'
                        // as per: http://tools.ietf.org/html/rfc2616#section-14.11
                        _ = headers.Remove(HttpHeaderNames.ContentEncoding);
                    }
                    else
                    {
                        _ = headers.Set(HttpHeaderNames.ContentEncoding, targetContentEncoding);
                    }

                    if (httpContent is object)
                    {
                        // If message is a full request or response object (headers + data), don't copy data part into out.
                        // Output headers only; data part will be decoded below.
                        // Note: "copy" object must not be an instance of LastHttpContent class,
                        // as this would (erroneously) indicate the end of the HttpMessage to other handlers.
                        IHttpMessage copy = null;
                        switch (httpMessage)
                        {
                        case IHttpRequest req:
                            // HttpRequest or FullHttpRequest
                            copy = new DefaultHttpRequest(req.ProtocolVersion, req.Method, req.Uri);
                            break;

                        case IHttpResponse res:
                            // HttpResponse or FullHttpResponse
                            copy = new DefaultHttpResponse(res.ProtocolVersion, res.Status);
                            break;

                        default:
                            ThrowHelper.ThrowCodecException_InvalidHttpMsg(httpMessage);
                            break;
                        }
                        _           = copy.Headers.Set(httpMessage.Headers);
                        copy.Result = httpMessage.Result;
                        output.Add(copy);
                    }
                    else
                    {
                        output.Add(httpMessage);
                    }
                }

                if (httpContent is object)
                {
                    if (this.decoder is null)
                    {
                        output.Add(httpContent.Retain());
                    }
                    else
                    {
                        this.DecodeContent(httpContent, output);
                    }
                }
            }
            finally
            {
                _needRead = 0u >= (uint)output.Count;
            }
        }
Example #51
0
 public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
 {
     ChannelInactive(context);
     //Logger.Error(exception, "Unhandled exception");
 }
Example #52
0
 protected abstract void Decode(IChannelHandlerContext context, IByteBuf input, List <object> output);
Example #53
0
 public override void ChannelReadComplete(IChannelHandlerContext context)
 {
     context.Flush();
 }
Example #54
0
        protected void CallDecode(IChannelHandlerContext context, IByteBuf input, List <object> output)
        {
            try
            {
                while (input.IsReadable())
                {
                    var outSize = output.Count;
                    if (outSize > 0)
                    {
                        FireChannelRead(context, output, outSize);
                        output.Clear();

                        // Check if this handler was removed before continuing with decoding
                        // If it was removed, it is no longer safe to keep operating on the buffer
                        if (context.Removed)
                        {
                            break;
                        }

                        outSize = 0;
                    }

                    var oldInputLength = input.ReadableBytes;
                    Decode(context, input, output);

                    // Check if this handler was removed before continuing with decoding
                    // If it was removed, it is no longer safe to keep operating on the buffer
                    if (context.Removed)
                    {
                        break;
                    }

                    if (outSize == output.Count)
                    {
                        if (oldInputLength == input.ReadableBytes)
                        {
                            break;
                        }
                        continue;
                    }

                    if (oldInputLength == input.ReadableBytes)
                    {
                        throw new DecoderException($"{GetType()}.Decode() did not read anything but decoded a message.");
                    }

                    if (IsSingleDecode)
                    {
                        break;
                    }
                }
            }
            catch (DecoderException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new DecoderException(ex);
            }
        }
            public async override Task CloseAsync(IChannelHandlerContext context)
            {
                await RemoveServiceProvider(context);

                await base.CloseAsync(context);
            }
Example #56
0
 public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
 {
     logger.LogError(exception, exception.Message);
 }
            public async override void ChannelActive(IChannelHandlerContext context)
            {
                await MarkServiceProviderHealth(context);

                base.ChannelActive(context);
            }
            public async override void ChannelInactive(IChannelHandlerContext context)
            {
                await RemoveServiceProvider(context);

                base.ChannelInactive(context);
            }
Example #59
0
        protected override void ChannelRead0(IChannelHandlerContext ctx, DatagramPacket packet)
        {
            logger.LogDebug("Received => {0}", packet);
            if (!packet.Content.IsReadable())
            {
                return;
            }


            try
            {
                var received = packet.Content;


                if (received.ToString(Encoding.ASCII).StartsWith("conn_ack"))
                {
                    Connected?.Invoke(this, EventArgs.Empty);

                    // requestIframe();
                    //for(int i=74;i<80;i++)
                    //queryUnk(i);
                    //Console.WriteLine("Tello connected!");
                    return;
                }


                //received
                var cmdId = received.GetShortLE(5);

                // int cmdId = (received.GetInt(5) | ((int)received.bytes[6] << 8));

                if (cmdId >= 74 && cmdId < 80)
                {
                    //Console.WriteLine("XXXXXXXXCMD:" + cmdId);
                }
                //if (cmdId == 86)//state command
                //{
                //    //update
                //    state.set(received.bytes.Skip(9).ToArray());

                //}
                //if (cmdId == 4176)//log header
                //{
                //    //just ack.
                //    var id = BitConverter.ToUInt16(received.bytes, 9);
                //    sendAckLog((short)cmdId, id);
                //    //Console.WriteLine(id);
                //}
                //if (cmdId == 4177)//log data
                //{
                //    state.parseLog(received.bytes.Skip(10).ToArray());
                //}
                //if (cmdId == 4178)//log config
                //{
                //    //todo. this doesnt seem to be working.

                //    //var id = BitConverter.ToUInt16(received.bytes, 9);
                //    //var n2 = BitConverter.ToInt32(received.bytes, 11);
                //    //sendAckLogConfig((short)cmdId, id,n2);

                //    //var dataStr = BitConverter.ToString(received.bytes.Skip(14).Take(10).ToArray()).Replace("-", " ")/*+"  "+pos*/;


                //    //Console.WriteLine(dataStr);
                //}
                //if (cmdId == 4185)//att angle response
                //{
                //    var array = received.bytes.Skip(10).Take(4).ToArray();
                //    float f = BitConverter.ToSingle(array, 0);
                //    Console.WriteLine(f);
                //}
                //if (cmdId == 4182)//max hei response
                //{
                //    //var array = received.bytes.Skip(9).Take(4).Reverse().ToArray();
                //    //float f = BitConverter.ToSingle(array, 0);
                //    //Console.WriteLine(f);
                //    if (received.bytes[10] != 10)
                //    {

                //    }
                //}
                //if (cmdId == 26)//wifi str command
                //{
                //    wifiStrength = received.bytes[9];
                //    if (received.bytes[10] != 0)//Disturb?
                //    {
                //    }
                //}
                //if (cmdId == 53)//light str command
                //{
                //}
                //if (cmdId == 98)//start jpeg.
                //{
                //    picFilePath = picPath + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".jpg";

                //    var start = 9;
                //    var ftype = received.bytes[start];
                //    start += 1;
                //    picBytesExpected = BitConverter.ToUInt32(received.bytes, start);
                //    if (picBytesExpected > picbuffer.Length)
                //    {
                //        Console.WriteLine("WARNING:Picture Too Big! " + picBytesExpected);
                //        picbuffer = new byte[picBytesExpected];
                //    }
                //    picBytesRecived = 0;
                //    picChunkState = new bool[(picBytesExpected / 1024) + 1]; //calc based on size.
                //    picPieceState = new bool[(picChunkState.Length / 8) + 1];
                //    picExtraPackets = 0;//for debugging.
                //    picDownloading = true;

                //    sendAckFileSize();
                //}
                //if (cmdId == 99)//jpeg
                //{
                //    //var dataStr = BitConverter.ToString(received.bytes.Skip(0).Take(30).ToArray()).Replace("-", " ");

                //    var start = 9;
                //    var fileNum = BitConverter.ToUInt16(received.bytes, start);
                //    start += 2;
                //    var pieceNum = BitConverter.ToUInt32(received.bytes, start);
                //    start += 4;
                //    var seqNum = BitConverter.ToUInt32(received.bytes, start);
                //    start += 4;
                //    var size = BitConverter.ToUInt16(received.bytes, start);
                //    start += 2;

                //    maxPieceNum = Math.Max((int)pieceNum, maxPieceNum);
                //    if (!picChunkState[seqNum])
                //    {
                //        Array.Copy(received.bytes, start, picbuffer, seqNum * 1024, size);
                //        picBytesRecived += size;
                //        picChunkState[seqNum] = true;

                //        for (int p = 0; p < picChunkState.Length / 8; p++)
                //        {
                //            var done = true;
                //            for (int s = 0; s < 8; s++)
                //            {
                //                if (!picChunkState[(p * 8) + s])
                //                {
                //                    done = false;
                //                    break;
                //                }
                //            }
                //            if (done && !picPieceState[p])
                //            {
                //                picPieceState[p] = true;
                //                sendAckFilePiece(0, fileNum, (UInt32)p);
                //                //Console.WriteLine("\nACK PN:" + p + " " + seqNum);
                //            }
                //        }
                //        if (picFilePath != null && picBytesRecived >= picBytesExpected)
                //        {
                //            picDownloading = false;

                //            sendAckFilePiece(1, 0, (UInt32)maxPieceNum);//todo. Double check this. finalize

                //            sendAckFileDone((int)picBytesExpected);

                //            //HACK.
                //            //Send file done cmdId to the update listener so it knows the picture is done.
                //            //hack.
                //            onUpdate(100);
                //            //hack.
                //            //This is a hack because it is faking a message. And not a very good fake.
                //            //HACK.

                //            Console.WriteLine("\nDONE PN:" + pieceNum + " max: " + maxPieceNum);

                //            //Save raw data minus sequence.
                //            using (var stream = new FileStream(picFilePath, FileMode.Append))
                //            {
                //                stream.Write(picbuffer, 0, (int)picBytesExpected);
                //            }
                //        }
                //    }
                //    else
                //    {
                //        picExtraPackets++;//for debugging.

                //        //if(picBytesRecived >= picBytesExpected)
                //        //    Console.WriteLine("\nEXTRA PN:"+pieceNum+" max "+ maxPieceNum);
                //    }


                //}
                //if (cmdId == 100)
                //{

                //}

                ////send command to listeners.
                //try
                //{
                //    //fire update event.
                //    onUpdate(cmdId);
                //}
                //catch (Exception ex)
                //{
                //    //Fixed. Update errors do not cause disconnect.
                //    Console.WriteLine("onUpdate error:" + ex.Message);
                //    //break;
                //}
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                //Console.WriteLine("Receive thread error:" + ex.Message);
                //disconnect();
                //break;
            }
        }
Example #60
0
 public override void HandlerAdded(IChannelHandlerContext context)
 {
     this.HandlerContext = context;
     base.HandlerAdded(context);
 }