Пример #1
0
        void ContinueScenarioExecution(IChannelHandlerContext context)
        {
            if (!this.testScenario.MoveNext())
            {
                context.CloseAsync()
                    .ContinueWith(
                        t => this.completion.TrySetException(t.Exception),
                        TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
                this.completion.TryComplete();
                return;
            }
            foreach (object message in this.testScenario.Current.SendMessages)
            {
                context.WriteAsync(message)
                    .ContinueWith(
                        t => this.completion.TrySetException(t.Exception),
                        TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
            }

            context.Flush();
        }
Пример #2
0
 public void Flush(IChannelHandlerContext context)
 {
     context.Flush();
 }
Пример #3
0
 public override void Flush(IChannelHandlerContext ctx)
 {
     Logger().LogDebug($"Channel {ctx.Channel} flushing");
     ctx.Flush();
 }
Пример #4
0
 public static void NotifyHandshakeFailure(IChannelHandlerContext ctx, Exception cause)
 {
     // We have may haven written some parts of data before an exception was thrown so ensure we always flush.
     // See https://github.com/netty/netty/issues/3900#issuecomment-172481830
     ctx.Flush();
     ctx.FireUserEventTriggered(new TlsHandshakeCompletionEvent(cause));
     ctx.CloseAsync();
 }
        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.Schedule(
                    () => 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);
            }
        }
        async void ProcessPendingSubscriptionChanges(IChannelHandlerContext context)
        {
            try
            {
                do
                {
                    ISessionState newState = this.sessionState.Copy();
                    Queue<Packet> queue = this.SubscriptionChangeQueue;
                    var acks = new List<Packet>(queue.Count);
                    foreach (Packet packet in queue) // todo: if can queue be null here, don't force creation
                    {
                        switch (packet.PacketType)
                        {
                            case PacketType.SUBSCRIBE:
                                acks.Add(Util.AddSubscriptions(newState, (SubscribePacket)packet, this.maxSupportedQosToClient));
                                break;
                            case PacketType.UNSUBSCRIBE:
                                acks.Add(Util.RemoveSubscriptions(newState, (UnsubscribePacket)packet));
                                break;
                            default:
                                throw new ArgumentOutOfRangeException();
                        }
                    }
                    queue.Clear();

                    if (!this.sessionState.IsTransient)
                    {
                        // save updated session state, make it current once successfully set
                        await this.sessionStateManager.SetAsync(this.deviceId, newState);
                    }

                    this.sessionState = newState;

                    // release ACKs

                    var tasks = new List<Task>(acks.Count);
                    foreach (Packet ack in acks)
                    {
                        tasks.Add(context.WriteAsync(ack));
                    }
                    context.Flush();
                    await Task.WhenAll(tasks);
                    PerformanceCounters.PacketsSentPerSecond.IncrementBy(acks.Count);
                }
                while (this.subscriptionChangeQueue.Count > 0);

                this.ResetState(StateFlags.ChangingSubscriptions);
            }
            catch (Exception ex)
            {
                ShutdownOnError(context, "-> UN/SUBSCRIBE", ex);
            }
        }
Пример #7
0
 public override void ChannelActive(IChannelHandlerContext context)
 {
     // write a large enough blob of data that it has to be split into multiple writes
     var channel = context.Channel;
     _tasks.Enqueue(
         context.WriteAsync(context.Allocator.Buffer().WriteZero(1048576))
             .ContinueWith(tr => channel.CloseAsync(),
                 TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion)
             .Unwrap());
     _tasks.Enqueue(context.WriteAsync(context.Allocator.Buffer().WriteZero(1048576)));
     context.Flush();
     _tasks.Enqueue(context.WriteAsync(context.Allocator.Buffer().WriteZero(1048576)));
     context.Flush();
 }
        void DoFlush(IChannelHandlerContext context)
        {
            IChannel channel = context.Channel;

            if (!channel.Active)
            {
                this.Discard();
                return;
            }

            bool requiresFlush             = true;
            IByteBufferAllocator allocator = context.Allocator;

            while (channel.IsWritable)
            {
                if (this.currentWrite == null)
                {
                    this.currentWrite = this.queue.Count > 0 ? this.queue.Dequeue() : null;
                }

                if (this.currentWrite == null)
                {
                    break;
                }

                PendingWrite current        = this.currentWrite;
                object       pendingMessage = current.Message;

                if (pendingMessage is IChunkedInput <T> chunks)
                {
                    bool   endOfInput;
                    bool   suspend;
                    object message = null;

                    try
                    {
                        message    = chunks.ReadChunk(allocator);
                        endOfInput = chunks.IsEndOfInput;
                        if (message == null)
                        {
                            // No need to suspend when reached at the end.
                            suspend = !endOfInput;
                        }
                        else
                        {
                            suspend = false;
                        }
                    }
                    catch (Exception exception)
                    {
                        this.currentWrite = null;

                        if (message != null)
                        {
                            ReferenceCountUtil.Release(message);
                        }

                        current.Fail(exception);
                        CloseInput(chunks);

                        break;
                    }

                    if (suspend)
                    {
                        // ChunkedInput.nextChunk() returned null and it has
                        // not reached at the end of input. Let's wait until
                        // more chunks arrive. Nothing to write or notify.
                        break;
                    }

                    if (message == null)
                    {
                        // If message is null write an empty ByteBuf.
                        // See https://github.com/netty/netty/issues/1671
                        message = Unpooled.Empty;
                    }

                    Task future = context.WriteAsync(message);
                    if (endOfInput)
                    {
                        this.currentWrite = null;

                        // Register a listener which will close the input once the write is complete.
                        // This is needed because the Chunk may have some resource bound that can not
                        // be closed before its not written.
                        //
                        // See https://github.com/netty/netty/issues/303
                        future.ContinueWith((_, state) =>
                        {
                            var pendingTask = (PendingWrite)state;
                            CloseInput((IChunkedInput <T>)pendingTask.Message);
                            pendingTask.Success();
                        },
                                            current,
                                            TaskContinuationOptions.ExecuteSynchronously);
                    }
                    else if (channel.IsWritable)
                    {
                        future.ContinueWith((task, state) =>
                        {
                            var pendingTask = (PendingWrite)state;
                            if (task.IsFaulted)
                            {
                                CloseInput((IChunkedInput <T>)pendingTask.Message);
                                pendingTask.Fail(task.Exception);
                            }
                            else
                            {
                                pendingTask.Progress(chunks.Progress, chunks.Length);
                            }
                        },
                                            current,
                                            TaskContinuationOptions.ExecuteSynchronously);
                    }
                    else
                    {
                        future.ContinueWith((task, state) =>
                        {
                            var handler = (ChunkedWriteHandler <T>)state;
                            if (task.IsFaulted)
                            {
                                CloseInput((IChunkedInput <T>)handler.currentWrite.Message);
                                handler.currentWrite.Fail(task.Exception);
                            }
                            else
                            {
                                handler.currentWrite.Progress(chunks.Progress, chunks.Length);
                                if (channel.IsWritable)
                                {
                                    handler.ResumeTransfer();
                                }
                            }
                        },
                                            this,
                                            TaskContinuationOptions.ExecuteSynchronously);
                    }

                    // Flush each chunk to conserve memory
                    context.Flush();
                    requiresFlush = false;
                }
                else
                {
                    context.WriteAsync(pendingMessage)
                    .ContinueWith((task, state) =>
                    {
                        var pendingTask = (PendingWrite)state;
                        if (task.IsFaulted)
                        {
                            pendingTask.Fail(task.Exception);
                        }
                        else
                        {
                            pendingTask.Success();
                        }
                    },
                                  current,
                                  TaskContinuationOptions.ExecuteSynchronously);

                    this.currentWrite = null;
                    requiresFlush     = true;
                }

                if (!channel.Active)
                {
                    this.Discard(new ClosedChannelException());
                    break;
                }
            }

            if (requiresFlush)
            {
                context.Flush();
            }
        }
 public void ChannelReadComplete(IChannelHandlerContext ctx)
 {
     ctx.Flush();
 }
Пример #10
0
 public override void ChannelReadComplete(IChannelHandlerContext context)
 {
     context.Flush();
     //base.ChannelReadComplete(context);
 }
 public IChannelHandlerContext Flush()
 {
     _ = _ctx.Flush();
     return(this);
 }
Пример #12
0
        protected override void ChannelRead0(IChannelHandlerContext ctx, string msg)
        {
            if (msg == null)
            {
                throw new ArgumentNullException(nameof(msg));
            }

            Channel msgChannel;

            try
            {
                msgChannel = JsonConvert.DeserializeObject <Channel>(msg);
            }
            catch (Exception ex)
            {
                Logger.Log.Error(
                    string.Format(LogLanguage.Instance.GetMessageFromKey(LanguageKey.UNRECOGNIZED_MASTER_PACKET), ex));
                return;
            }

            if (!IsAuthenticated)
            {
                if (msgChannel.Password == Password)
                {
                    IsAuthenticated = true;
                    Logger.Log.Debug(string.Format(
                                         LogLanguage.Instance.GetMessageFromKey(LanguageKey.AUTHENTICATED_SUCCESS), _id.ToString()));

                    if (MasterClientListSingleton.Instance.WorldServers == null)
                    {
                        MasterClientListSingleton.Instance.WorldServers = new List <WorldServerInfo>();
                    }

                    try
                    {
                        _id = MasterClientListSingleton.Instance.WorldServers.Select(s => s.Id).Max() + 1;
                    }
                    catch
                    {
                        _id = 0;
                    }

                    var servtype = (ServerType)Enum.Parse(typeof(ServerType), msgChannel.ClientType.ToString());
                    if (servtype == ServerType.WorldServer)
                    {
                        var serv = new WorldServerInfo
                        {
                            Name = msgChannel.ClientName,
                            Host = msgChannel.Host,
                            Port = msgChannel.Port,
                            Id   = _id,
                            connectedAccountLimit = msgChannel.connectedAccountLimit,
                            WebApi = msgChannel.WebApi
                        };

                        MasterClientListSingleton.Instance.WorldServers.Add(serv);
                        msgChannel.ChannelId = _id;
                        WriteAsync(ctx, msgChannel);
                    }

                    ctx.Flush();
                }
                else
                {
                    ctx.CloseAsync();
                    Logger.Log.Error(
                        string.Format(LogLanguage.Instance.GetMessageFromKey(LanguageKey.AUTHENTICATED_ERROR)));
                }
            }
        }
Пример #13
0
        public override void ChannelReadComplete(IChannelHandlerContext context)
        {
            string Success = string.Empty;

            context.Flush();
        }
Пример #14
0
 public override void Flush(IChannelHandlerContext context)
 {
     RegisterFiredEvent(SupportedEvent.Flush);
     context.Flush();
 }
 public override void Flush(IChannelHandlerContext context)
 {
     context.Flush();
 }
Пример #16
0
 public override void Flush(IChannelHandlerContext context)
 {
     Log(Event.FLUSH);
     context.Flush();
 }
Пример #17
0
 /// <summary>
 /// Is called when a read timeout was detected.
 /// </summary>
 /// <param name="context">Context.</param>
 protected virtual void ReadTimedOut(IChannelHandlerContext context)
 {
     if(!this.closed)
     {
         context.FireExceptionCaught(ReadTimeoutException.Instance);
         context.Flush();
         this.closed = true;
     }
 }
Пример #18
0
        public override void Flush(IChannelHandlerContext context)
        {
            Log.Debug($"{context.Name}: Flush");

            context.Flush();
        }
Пример #19
0
 public override void ChannelReadComplete(IChannelHandlerContext context) => context?.Flush();
 public override void ChannelReadComplete(IChannelHandlerContext context)
 {
     base.ChannelReadComplete(context);
     context.Flush();
     RecordLogEvent?.Invoke("ChannelReadComplete:" + context);
 }
Пример #21
0
 public override void Flush(IChannelHandlerContext ctx)
 {
     if (this.Logger.IsEnabled(this.InternalLevel))
     {
         this.Logger.Log(this.InternalLevel, this.Format(ctx, "FLUSH"));
     }
     ctx.Flush();
 }
Пример #22
0
 /// <summary>
 /// 消息接收完毕
 /// </summary>
 /// <param name="context">通道处理上下文</param>
 public override void ChannelReadComplete(IChannelHandlerContext context)
 {
     base.ChannelReadComplete(context);
     context.Flush();
     ClientEventHandler.RecordLogEvent?.Invoke(true, "ChannelReadComplete");
 }
Пример #23
0
 public void Flush(IChannelHandlerContext context)
 {
     context.Flush();
 }
Пример #24
0
 public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush(); public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
Пример #25
0
 public override void ChannelReadComplete(IChannelHandlerContext context)
 {
     context.Flush();
 }
Пример #26
0
 public override void Flush(IChannelHandlerContext ctx)
 {
     log.Debug("Channel {0} flushing", ctx.Channel);
     ctx.Flush();
 }
Пример #27
0
 public virtual void Flush(IChannelHandlerContext context) => context.Flush();
Пример #28
0
 private void FlushNow(IChannelHandlerContext ctx)
 {
     CancelScheduledFlush();
     _flushPendingCount = 0;
     ctx.Flush();
 }