public void TcpServerSocketChannel_horizontal_scale_stress_test(BenchmarkContext context)
        {
            _clientConnectedCounter.Increment(); // for the initial client
            var totalRunSeconds = TotalRunSeconds;

            Console.WriteLine("Running benchmark for {0} minutes", totalRunSeconds.TotalMinutes);
            var deadline    = new PreciseDeadline(totalRunSeconds);
            var due         = DateTime.Now + totalRunSeconds;
            var lastMeasure = due;
            var task        = Task.Factory.StartNew(_eventLoop); // start writing
            var runCount    = 1;

            while (!deadline.IsOverdue)
            {
                // add a new client
                _clientChannels.Add(ClientBootstrap.ConnectAsync(_serverChannel.LocalAddress).Result);
                _clientConnectedCounter.Increment();
                Thread.Sleep(SleepInterval);
                if (++runCount % 10 == 0)
                {
                    Console.WriteLine("{0} minutes remaining [{1} connections active].",
                                      (due - DateTime.Now).TotalMinutes, runCount);
                    var saturation = (DateTime.Now - lastMeasure);
                    if (saturation > SaturationThreshold)
                    {
                        Console.WriteLine(
                            "Took {0} to create 10 connections; exceeded pre-defined saturation threshold of {1}. Ending stress test.",
                            saturation, SaturationThreshold);
                        break;
                    }
                    lastMeasure = DateTime.Now;
                }
            }
            _shutdownBenchmark.Cancel();
        }
            protected override ITcpServerSocketModel RunInternal(ITcpServerSocketModel obj0)
            {
                var cb = new ClientBootstrap()
                         .Group(ClientEventLoopGroup)
                         .Channel <TcpSocketChannel>()
                         .Handler(new ActionChannelInitializer <TcpSocketChannel>(ConstructClientPipeline));

                var connectTasks = new List <Task <IChannel> >();

                for (var i = 0; i < ClientCount; i++)
                {
                    connectTasks.Add(cb.ConnectAsync(obj0.BoundAddress));
                }

                if (!Task.WaitAll(connectTasks.ToArray(), TimeSpan.FromSeconds(ClientCount * 2)))
                {
                    throw new TimeoutException(
                              $"Waited {ClientCount} seconds to connect {ClientCount} clients to {obj0.BoundAddress}, but the operation timed out.");
                }

                foreach (var task in connectTasks)
                {
                    // storing our local address for comparison purposes
                    obj0 = obj0.AddLocalChannel(task.Result).AddClient((IPEndPoint)task.Result.LocalAddress);
                }
                return(obj0);
            }
Exemplo n.º 3
0
        public static Task <IChannel> CreateConnection(Role role, IPEndPoint socketAddress, int poolSize, IChannelHandler upstreamHandler)
        {
            if (role == Role.Client)
            {
                var connection = new ClientBootstrap()
                                 .ChannelFactory(() => new TcpSocketChannel(socketAddress.AddressFamily))
                                 .Option(ChannelOption.TcpNodelay, true)
                                 .Group(GetClientWorkerPool(poolSize))
                                 .Handler(new ActionChannelInitializer <TcpSocketChannel>(channel =>
                {
                    ApplyChannelPipeline(channel, upstreamHandler);
                }));

                return(connection.ConnectAsync(socketAddress));
            }
            else //server
            {
                var connection = new ServerBootstrap()
                                 .Group(GetServerPool(poolSize), GetServerWorkerPool(poolSize))
                                 .ChannelFactory(() => new TcpServerSocketChannel(socketAddress.AddressFamily))
                                 .ChildOption(ChannelOption.TcpNodelay, true)
                                 .ChildHandler(new ActionChannelInitializer <TcpSocketChannel>(channel =>
                {
                    ApplyChannelPipeline(channel, upstreamHandler);
                }));
                return(connection.BindAsync(socketAddress));
            }
        }
Exemplo n.º 4
0
        public void LocalChannel_WriteAsync_should_fail_fast_on_closed_channel()
        {
            var cb = new ClientBootstrap();
            var sb = new ServerBootstrap();

            cb.Group(_group1).Channel <LocalChannel>().Handler(new TestHandler());

            sb.Group(_group2).Channel <LocalServerChannel>().ChildHandler(new ActionChannelInitializer <LocalChannel>(
                                                                              channel => { channel.Pipeline.AddLast(new TestHandler()); }));

            IChannel sc = null;
            IChannel cc = null;

            try
            {
                // Start server
                sc = sb.BindAsync(TEST_ADDRESS).Result;
                var latch = new CountdownEvent(1);

                // Connect to the server
                cc = cb.ConnectAsync(sc.LocalAddress).Result;

                // Close the channel and write something
                cc.CloseAsync().Wait();
                var ag =
                    Assert.Throws <AggregateException>(() => { cc.WriteAndFlushAsync(new object()).Wait(); }).Flatten();
                Assert.IsType <ClosedChannelException>(ag.InnerException);
            }
            finally
            {
                CloseChannel(cc);
                CloseChannel(sc);
            }
        }
Exemplo n.º 5
0
        public void LocalServerChannel_should_be_able_to_close_channel_on_same_EventLoop()
        {
            var latch = new CountdownEvent(1);
            var sb    = new ServerBootstrap();

            sb.Group(_group2).Channel <LocalServerChannel>().ChildHandler(new ReadHandler1(latch));

            IChannel sc = null;
            IChannel cc = null;

            try
            {
                sc = sb.BindAsync(TEST_ADDRESS).Result;

                var b = new ClientBootstrap()
                        .Group(_group2)
                        .Channel <LocalChannel>().Handler(new ReadHandler2());
                cc = b.ConnectAsync(sc.LocalAddress).Result;
                cc.WriteAndFlushAsync(new object());
                Assert.True(latch.Wait(TimeSpan.FromSeconds(5)));
            }
            finally
            {
                CloseChannel(cc);
                CloseChannel(sc);
            }
        }
Exemplo n.º 6
0
        private static void CreateClient()
        {
            var channelConfig = new ChannelConfig()
            {
                AutoReceiving          = true,
                PenddingMessageCounter = 102400,
                ReceivingBufferSize    = 1024 * 64,
                SendingBufferSize      = 1024 * 64
            };


            var workGroup = new MutlEventloopGroup(1);

            var bootstrap = new ClientBootstrap();

            bootstrap
            .Group(workGroup)
            .Channel <TcpClientChannel>()
            .Config(channelConfig)
            .Pipeline(pipeline =>
            {
                pipeline.AddLast("Tls", new TlsHandler());
                pipeline.AddLast("Enc", new LengthMessageEncoder());
                pipeline.AddLast("Dec", new LengthMessageDecoder());
                pipeline.AddLast("MyChannelHandler", new MyChannelHandler());
            });
            bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse("192.168.1.103"), 46456));
        }
Exemplo n.º 7
0
        public void TcpSocketChannel_can_connect_to_TcpServerSocketChannel()
        {
            IEventLoopGroup group1 = new MultithreadEventLoopGroup(2);
            IEventLoopGroup group2 = new MultithreadEventLoopGroup(2);

            var cb         = new ClientBootstrap();
            var sb         = new ServerBootstrap();
            var reads      = 100;
            var resetEvent = new ManualResetEventSlim();

            cb.Group(group1)
            .Channel <TcpSocketChannel>()
            .Handler(
                new ActionChannelInitializer <TcpSocketChannel>(
                    channel =>
            {
                channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                .AddLast(new LengthFieldPrepender(4, false))
                .AddLast(new IntCodec())
                .AddLast(new TestHandler());
            }));

            sb.Group(group2)
            .Channel <TcpServerSocketChannel>()
            .ChildHandler(
                new ActionChannelInitializer <TcpSocketChannel>(
                    channel =>
            {
                channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                .AddLast(new LengthFieldPrepender(4, false))
                .AddLast(new IntCodec())
                .AddLast(new ReadCountAwaiter(resetEvent, reads))
                .AddLast(new TestHandler());
            }));

            IChannel sc = null;
            IChannel cc = null;

            try
            {
                // Start server
                sc = sb.BindAsync(TEST_ADDRESS).Result;

                // Connect to the server
                cc = cb.ConnectAsync(sc.LocalAddress).Result;

                foreach (var read in Enumerable.Range(0, reads))
                {
                    cc.WriteAndFlushAsync(read);
                }
                Assert.True(resetEvent.Wait(15000));
            }
            finally
            {
                CloseChannel(cc);
                CloseChannel(sc);
                Task.WaitAll(group1.ShutdownGracefullyAsync(), group2.ShutdownGracefullyAsync());
            }
        }
Exemplo n.º 8
0
        public void TcpSocketServerChannel_can_be_connected_to_on_any_aliased_Endpoint(IpMapping actual,
                                                                                       IpMapping alias, AddressFamily family)
        {
            var inboundActual = MappingToEndpoint(actual);
            var inboundAlias  = MappingToEndpoint(alias);
            var isIp          = inboundAlias is IPEndPoint;

            if (IsMono && family == AddressFamily.InterNetworkV6)
            {
                Assert.True(true, "Mono currently does not support IPV6 in DNS resolution");
                return;
            }


            IChannel s = null;
            IChannel c = null;

            try
            {
                var sb = new ServerBootstrap()
                         .ChannelFactory(() => new TcpServerSocketChannel())
                         .PreferredDnsResolutionFamily(family)
                         .ChildHandler(new ActionChannelInitializer <TcpSocketChannel>(channel => { }))
                         .Group(_serverGroup);

                s = sb.BindAsync(inboundActual).Result;


                var cb = new ClientBootstrap()
                         .ChannelFactory(() => new TcpSocketChannel())
                         .Option(ChannelOption.TcpNodelay, true)
                         .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(100))
                         .PreferredDnsResolutionFamily(family)
                         .Handler(new ActionChannelInitializer <TcpSocketChannel>(channel => { }))
                         .Group(_clientGroup);

                EndPoint clientEp = isIp
                    ? new IPEndPoint(((IPEndPoint)inboundAlias).Address, ((IPEndPoint)s.LocalAddress).Port)
                    : (EndPoint) new DnsEndPoint(((DnsEndPoint)inboundAlias).Host, ((IPEndPoint)s.LocalAddress).Port);

                c = cb.ConnectAsync(clientEp).Result;
                c.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(2)).Wait(20);

                Assert.True(c.IsOpen);
                Assert.True(c.IsActive);
                Assert.True(c.IsWritable);
            }
            finally
            {
                try
                {
                    c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                    s?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                }
                catch
                {
                }
            }
        }
Exemplo n.º 9
0
        public Property TcpServerSocketChannel_can_accept_connection_on_any_valid_Endpoint(EndPoint ep)
        {
            var ip = ep as IPEndPoint;


            IChannel s = null;
            IChannel c = null;

            try
            {
                var sb = new ServerBootstrap()
                         .Channel <TcpServerSocketChannel>()
                         .ChildHandler(new ActionChannelInitializer <TcpSocketChannel>(channel => { }))
                         .Group(_serverGroup);

                s = sb.BindAsync(ep).Result;

                var cb = new ClientBootstrap()
                         .Channel <TcpSocketChannel>()
                         .Option(ChannelOption.TcpNodelay, true)
                         .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(100))
                         .Handler(new ActionChannelInitializer <TcpSocketChannel>(channel => { }))
                         .Group(_clientGroup);

                var clientEp = s.LocalAddress;
                if (ip != null) // handle special case of 0.0.0.0, which clients can't connect to directly.
                {
                    if (ip.Address.Equals(IPAddress.Any))
                    {
                        clientEp = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)s.LocalAddress).Port);
                    }
                    if (ip.Address.Equals(IPAddress.IPv6Any))
                    {
                        clientEp = new IPEndPoint(IPAddress.IPv6Loopback, ((IPEndPoint)s.LocalAddress).Port);
                    }
                }

                c = cb.ConnectAsync(clientEp).Result;
                c.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(2)).Wait(20);

                return(c.IsOpen.Label("Channel should be open")
                       .And(c.IsActive).Label("Channel should be active")
                       .And(c.IsWritable).Label("Channel should be writable"));
            }
            finally
            {
                try
                {
                    c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                    s?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                }
                catch
                {
                }
            }
        }
Exemplo n.º 10
0
        public void LocalChannel_writes_to_server_should_be_read_by_LocalChannel()
        {
            var cb               = new ClientBootstrap();
            var sb               = new ServerBootstrap();
            var reads            = new[] { -11, 2, 9, 13, 1013, 1, 4 };
            var resetEvent       = new ManualResetEventSlim();
            var accumulatedReads = new List <int>();

            cb.Group(_group1)
            .Channel <LocalChannel>()
            .Handler(
                new ActionChannelInitializer <LocalChannel>(
                    channel =>
            {
                channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                .AddLast(new LengthFieldPrepender(4, false))
                .AddLast(new IntCodec());
            }));

            sb.Group(_group2)
            .Channel <LocalServerChannel>()
            .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    channel =>
            {
                channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                .AddLast(new LengthFieldPrepender(4, false))
                .AddLast(new IntCodec())
                .AddLast(new ReadAssertHandler(accumulatedReads, resetEvent, reads));
            }));

            IChannel sc = null;
            IChannel cc = null;

            try
            {
                // Start server
                sc = sb.BindAsync(TEST_ADDRESS).Result;

                // Connect to the server
                cc = cb.ConnectAsync(sc.LocalAddress).Result;

                foreach (var read in reads)
                {
                    cc.WriteAsync(read);
                }
                cc.Flush();
                resetEvent.Wait(200);
                Assert.Equal(reads, accumulatedReads);
            }
            finally
            {
                CloseChannel(sc);
                CloseChannel(cc);
            }
        }
Exemplo n.º 11
0
        public void LocalChannel_write_when_WritePromiseComplete_should_still_preserve_order()
        {
            var cb           = new ClientBootstrap();
            var sb           = new ServerBootstrap();
            var messageLatch = new CountdownEvent(2);
            var data1        = Unpooled.WrappedBuffer(new byte[1024]);
            var data2        = Unpooled.WrappedBuffer(new byte[512]);

            try
            {
                cb.Group(_group1)
                .Channel <LocalChannel>()
                .Handler(new TestHandler());

                sb.Group(_group2)
                .Channel <LocalServerChannel>()
                .ChildHandler(new ReadCountdown2(messageLatch, data1, data2));

                IChannel sc = null;
                IChannel cc = null;

                try
                {
                    // Start server
                    sc = sb.BindAsync(TEST_ADDRESS).Result;

                    // Connect to server
                    cc = cb.ConnectAsync(sc.LocalAddress).Result;

                    var ccCpy = cc;

                    // Make sure a write operation is executed in the eventloop
                    cc.Pipeline.LastContext().Executor.Execute(() =>
                    {
                        Logger.Info("Writing message 1");
                        ccCpy.WriteAndFlushAsync(data1.Duplicate().Retain()).ContinueWith(tr =>
                        {
                            Logger.Info("Writing message 2");
                            ccCpy.WriteAndFlushAsync(data2.Duplicate().Retain());
                        });
                    });

                    Assert.True(messageLatch.Wait(TimeSpan.FromSeconds(5)));
                }
                finally
                {
                    CloseChannel(sc);
                    CloseChannel(cc);
                }
            }
            finally
            {
                data1.Release();
                data2.Release();
            }
        }
Exemplo n.º 12
0
        public async Task TcpSocketChannel_should_not_throw_on_shutdown()
        {
            AtomicReference <Exception> clientError = new AtomicReference <Exception>(null);
            AtomicReference <Exception> serverError = new AtomicReference <Exception>(null);

            IChannel s = null;
            IChannel c = null;

            try
            {
                var sb = new ServerBootstrap()
                         .Channel <TcpServerSocketChannel>()
                         .ChildHandler(
                    new ActionChannelInitializer <TcpSocketChannel>(
                        channel => { channel.Pipeline.AddLast(new FailAssertionHandler(serverError)); }))
                         .Group(_serverGroup);

                s = sb.BindAsync(new IPEndPoint(IPAddress.IPv6Loopback, 0)).Result;


                var cb = new ClientBootstrap()
                         .Channel <TcpSocketChannel>()
                         .Option(ChannelOption.TcpNodelay, true)
                         .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(100))
                         .Handler(
                    new ActionChannelInitializer <TcpSocketChannel>(
                        channel => { channel.Pipeline.AddLast(new FailAssertionHandler(clientError)); }))
                         .Group(_clientGroup);

                var clientEp = s.LocalAddress;
                c = cb.ConnectAsync(clientEp).Result;
                c.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(2)).Wait(20);
                Assert.True(c.IsOpen);
                await c.CloseAsync();

                // assert that the counters were never decremented
                Assert.True(clientError.Value == null,
                            $"Expected null but error on client was {clientError.Value?.Message} {clientError.Value?.StackTrace}");
                Assert.True(serverError.Value == null,
                            $"Expected null but error on server was {serverError.Value?.Message} {serverError.Value?.StackTrace}");
            }
            finally
            {
                try
                {
                    c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                    s?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                }
                catch
                {
                }
            }
        }
Exemplo n.º 13
0
        public void LocalChannel_batch_read_should_not_NRE()
        {
            var cb         = new ClientBootstrap();
            var sb         = new ServerBootstrap();
            var reads      = 100;
            var resetEvent = new ManualResetEventSlim();

            cb.Group(_group1)
            .Channel <LocalChannel>()
            .Handler(
                new ActionChannelInitializer <LocalChannel>(
                    channel =>
            {
                channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                .AddLast(new LengthFieldPrepender(4, false))
                .AddLast(new TestHandler());
            }));

            sb.Group(_group2)
            .Channel <LocalServerChannel>()
            .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    channel =>
            {
                channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                .AddLast(new LengthFieldPrepender(4, false))
                .AddLast(new ReadCountAwaiter(resetEvent, reads))
                .AddLast(new TestHandler());
            }));

            IChannel sc = null;
            IChannel cc = null;

            try
            {
                // Start server
                sc = sb.BindAsync(TEST_ADDRESS).Result;

                // Connect to the server
                cc = cb.ConnectAsync(sc.LocalAddress).Result;

                foreach (var read in Enumerable.Range(0, reads))
                {
                    cc.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(read));
                }
                Assert.True(resetEvent.Wait(5000));
            }
            finally
            {
                CloseChannel(sc);
                CloseChannel(cc);
            }
        }
Exemplo n.º 14
0
        public void SetUp(BenchmarkContext context)
        {
            ClientGroup = new MultithreadEventLoopGroup(1);
            ServerGroup = new MultithreadEventLoopGroup(1);
            WorkerGroup = new MultithreadEventLoopGroup();


            var iso = Encoding.GetEncoding("ISO-8859-1");

            message = iso.GetBytes("ABC");

            // pre-allocate all messages
            foreach (var m in Enumerable.Range(0, WriteCount))
            {
                messages[m] = Unpooled.WrappedBuffer(message);
            }

            _inboundThroughputCounter  = context.GetCounter(InboundThroughputCounterName);
            _outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName);
            var counterHandler = new CounterHandlerInbound(_inboundThroughputCounter);

            _signal = new ManualResetEventSlimReadFinishedSignal(ResetEvent);

            var sb = new ServerBootstrap().Group(ServerGroup, WorkerGroup).Channel <TcpServerSocketChannel>()
                     .ChildOption(ChannelOption.TcpNodelay, true)
                     .ChildHandler(
                new ActionChannelInitializer <TcpSocketChannel>(
                    channel =>
            {
                channel.Pipeline.AddLast(GetEncoder())
                .AddLast(GetDecoder())
                .AddLast(counterHandler)
                .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter))
                .AddLast(new ReadFinishedHandler(_signal, WriteCount));
            }));

            var cb = new ClientBootstrap().Group(ClientGroup)
                     .Option(ChannelOption.TcpNodelay, true)
                     .Channel <TcpSocketChannel>().Handler(new ActionChannelInitializer <TcpSocketChannel>(
                                                               channel =>
            {
                channel.Pipeline.AddLast(GetEncoder()).AddLast(GetDecoder()).AddLast(counterHandler)
                .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter));
            }));

            // start server
            _serverChannel = sb.BindAsync(TEST_ADDRESS).Result;

            // connect to server
            _clientChannel = cb.ConnectAsync(_serverChannel.LocalAddress).Result;
            //_clientChannel.Configuration.AutoRead = false;
        }
        public async Task TcpSocketChannel_should_not_throw_on_shutdown()
        {
            AtomicReference<Exception> clientError = new AtomicReference<Exception>(null);
            AtomicReference<Exception> serverError = new AtomicReference<Exception>(null);

            IChannel s = null;
            IChannel c = null;
            try
            {
                var sb = new ServerBootstrap()
                    .Channel<TcpServerSocketChannel>()
                    .ChildHandler(
                        new ActionChannelInitializer<TcpSocketChannel>(
                            channel => { channel.Pipeline.AddLast(new FailAssertionHandler(serverError)); }))
                    .Group(_serverGroup);

                s = sb.BindAsync(new IPEndPoint(IPAddress.IPv6Loopback, 0)).Result;


                var cb = new ClientBootstrap()
                    .Channel<TcpSocketChannel>()
                    .Option(ChannelOption.TcpNodelay, true)
                    .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(100))
                    .Handler(
                        new ActionChannelInitializer<TcpSocketChannel>(
                            channel => { channel.Pipeline.AddLast(new FailAssertionHandler(clientError)); }))
                    .Group(_clientGroup);

                var clientEp = s.LocalAddress;
                c = cb.ConnectAsync(clientEp).Result;
                c.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(2)).Wait(20);
                Assert.True(c.IsOpen);
                await c.CloseAsync();

                // assert that the counters were never decremented
                Assert.True(clientError.Value == null,
                    $"Expected null but error on client was {clientError.Value?.Message} {clientError.Value?.StackTrace}");
                Assert.True(serverError.Value == null,
                    $"Expected null but error on server was {serverError.Value?.Message} {serverError.Value?.StackTrace}");
            }
            finally
            {
                try
                {
                    c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                    s?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                }
                catch
                {
                }
            }
        }
Exemplo n.º 16
0
        public void LocalChannel_should_reuse_LocalAddress()
        {
            for (var i = 0; i < 2; i++)
            {
                var cb = new ClientBootstrap();
                var sb = new ServerBootstrap();

                cb.Group(_group1).Channel <LocalChannel>().Handler(new TestHandler());

                sb.Group(_group2).Channel <LocalServerChannel>().ChildHandler(new ActionChannelInitializer <LocalChannel>(
                                                                                  channel => { channel.Pipeline.AddLast(new TestHandler()); }));

                IChannel sc = null;
                IChannel cc = null;

                try
                {
                    // Start server
                    sc = sb.BindAsync(TEST_ADDRESS).Result;
                    var latch = new CountdownEvent(1);

                    // Connect to the server
                    cc = cb.ConnectAsync(sc.LocalAddress).Result;
                    var cCpy = cc;
                    cc.EventLoop.Execute(o =>
                    {
                        var c = (LocalChannel)o;
                        c.Pipeline.FireChannelRead("Hello, World");
                        latch.Signal();
                    }, cCpy);

                    latch.Wait(TimeSpan.FromSeconds(5));
                    Assert.True(latch.IsSet);

                    CloseChannel(cc);
                    CloseChannel(sc);
                    sc.CloseCompletion.Wait();

                    Assert.Null(LocalChannelRegistry.Get(TEST_ADDRESS));
                }
                finally
                {
                    CloseChannel(cc);
                    CloseChannel(sc);
                }
            }
        }
Exemplo n.º 17
0
        private async Task Test(ClientBootstrap bootstrap)
        {
            // var ip = "127.0.0.1";
            //ip="192.168.111.133";
            // int port = 8007;
            //  ip = "192.168.3.5";
            for (int i = 0; i < 10; i++)
            {
                Task.Run(async() =>
                {
                    //IChannel client = null;
                    //try
                    //{
                    //    client = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port));
                    //}
                    //catch (Exception ex)
                    //{
                    //    Console.WriteLine("**********" + ex.Message);
                    //}

                    //if (client != null) await Test(100, client);
                    for (int i = 0; i < 100000; i++)
                    {
                        IChannel client = null;
                        try
                        {
                            client = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port));
                            await Test(1, client);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                        finally
                        {
                            if (client != null)
                            {
                                await client?.CloseAsync();
                            }
                        }
                    }
                });

                // await Task.Delay(10);
            }
        }
Exemplo n.º 18
0
        public void SetUp(BenchmarkContext context)
        {
            ClientGroup = new MultithreadEventLoopGroup(1);
            ServerGroup = new MultithreadEventLoopGroup(2);

            var iso = Encoding.GetEncoding("ISO-8859-1");

            message = iso.GetBytes("ABC");

            _inboundThroughputCounter  = context.GetCounter(InboundThroughputCounterName);
            _outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName);
            var counterHandler = new CounterHandlerInbound(_inboundThroughputCounter);

            _signal = new SimpleReadFinishedSignal();

            var sb = new ServerBootstrap().Group(ServerGroup).Channel <LocalServerChannel>()
                     .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    channel =>
            {
                channel.Pipeline.AddLast(GetEncoder())
                .AddLast(GetDecoder())
                .AddLast(counterHandler)
                .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter))
                .AddLast(new ReadFinishedHandler(_signal, WriteCount));
            }));

            var cb =
                new ClientBootstrap().Group(ClientGroup)
                .Channel <LocalChannel>()
                .Handler(new ActionChannelInitializer <LocalChannel>(
                             channel =>
            {
                channel.Pipeline.AddLast(GetEncoder()).AddLast(GetDecoder()).AddLast(counterHandler)
                .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter));
            }));

            // start server
            _serverChannel = sb.BindAsync(TEST_ADDRESS).Result;

            // connect to server
            _clientChannel = cb.ConnectAsync(_serverChannel.LocalAddress).Result;
        }
        public void Helios20_Client_and_Helios14_Server_Should_ReadWrite()
        {
            IReactor server = null;
            IChannel client = null;

            try
            {
                server            = _serverBootstrap.NewReactor(NodeBuilder.BuildNode().Host(IPAddress.Loopback).WithPort(0));
                server.OnReceive += (data, channel) =>
                {
                    // echo the response back
                    channel.Send(data);
                };

                server.OnConnection += (address, channel) => { channel.BeginReceive(); };

                server.Start();
                client = _clientBootstrap.ConnectAsync(server.LocalEndpoint).Result;
                Task.Delay(TimeSpan.FromMilliseconds(500)).Wait(); // because Helios 1.4 is stupid
                var writes =
                    Enumerable.Range(0, ReadCount)
                    .Select(x => ThreadLocalRandom.Current.Next())
                    .OrderBy(y => y)
                    .ToList();
                foreach (var write in writes)
                {
                    client.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(write));
                }

                _resetEvent.Wait();
                var decodedReceive = _received.Select(y => y.ReadInt()).OrderBy(x => x).ToList();
                Assert.True(decodedReceive.SequenceEqual(writes));
            }
            finally
            {
                client?.CloseAsync().Wait();
                server?.Stop();
                _clientGroup.ShutdownGracefullyAsync().Wait();
            }
        }
Exemplo n.º 20
0
        public async Task Test()
        {
            int heartbeatIntervalSecond = 60;

            InternalLoggerFactory.DefaultFactory = _loggerFactory;//.AddConsoleLogger();

            //实际要考虑事件循环的共用,事件循环的关闭问题
            MultithreadEventLoopGroup workerGroup = new MultithreadEventLoopGroup(8);

            workerGroup.Start();

            var bootstrap = new ClientBootstrap();

            bootstrap
            .Group(workerGroup)
            .Config(ConfigConstant.HeartbeatIntervalSecond, heartbeatIntervalSecond)
            .Config(ConfigConstant.ConnectTimeoutSecond, 10)
            .Channel <TcpSocketChannel>()
            .WorkerHandler(channel =>
            {
                //channel.Pipeline.AddLast("MessageDecoder", new MessageDecoder());
                channel.Pipeline.AddLast("MessageBaseDecoder", new LengthFieldBasedFrameDecoder(int.MaxValue, 4, 4));
                channel.Pipeline.AddLast("MessageDecoder", new MessageDecoder());

                channel.Pipeline.AddLast("MessageEncoder", new MessageEncoder());
                channel.Pipeline.AddLast("IdleStateHandler", new IdleStateHandler(0, 0, heartbeatIntervalSecond));
                channel.Pipeline.AddLast("ClientHeartbeatHandler", new ClientHeartbeatHandler());
                channel.Pipeline.AddLast("ServerHandler", new ClientHandler());

                //便于理解 这里都是addlist 入站是从上外下执行的,出站是从下往上执行的
            });

            //这里创建连接 如果连接失败 会抛异常。如果连接成功以后,连接再断开会触发ChannelInactive 事件
            //可以管理连接封装起来,首次连接失败 通过捕获异常进行重试,连接后再断开在ChannelInactive 事件中 进行连接重试
            var client = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port));

            await Test(bootstrap);
        }
Exemplo n.º 21
0
        private void InitSocket()
        {
            new Thread(() => //new thread to run socket
            {
                clientBootstrap.ConnectAsync().ContinueWith(task =>
                {
                    //if connect success
                    echoHandler.channel = task.Result;
                    echoHandler.slim.Set();
                });
            })
            {
                IsBackground = true
            }.Start();

            echoHandler.slim.WaitOne(msgTimeout);
            if (echoHandler.channel == null)
            {
                throw new Exception("MyIdServer --> can not connect to " + server + ":" + port);
            }
            else //send login
            {
                echoHandler.sb.Clear();
                byte[] byteArry = Encoding.Default.GetBytes(pwd);
                echoHandler.channel.WriteAndFlushAsync(Unpooled.WrappedBuffer(byteArry));
                echoHandler.slim.WaitOne(msgTimeout);
                if (echoHandler.sb.ToString() == "-1")
                {
                    echoHandler.channel.CloseAsync();
                    echoHandler.channel = null;
                    echoHandler.slim.Reset();
                    echoHandler.sb.Clear();
                    throw new Exception("MyIdServer --> password error");
                }
            }
        }
Exemplo n.º 22
0
        public Property TcpServerSocketChannel_can_accept_connection_on_any_valid_Endpoint(EndPoint ep)
        {
            var ip     = ep as IPEndPoint;
            var family = ep.BestAddressFamily();

            // TODO: remove this code once https://bugzilla.xamarin.com/show_bug.cgi?id=35536 is fixed

            if (IsMono && family == AddressFamily.InterNetworkV6 && ep is DnsEndPoint)
            {
                family = AddressFamily.InterNetwork;
            }

            IChannel s = null;
            IChannel c = null;

            try
            {
                var sb = new ServerBootstrap()
                         .ChannelFactory(() => new TcpServerSocketChannel(family))
                         .ChildHandler(new ActionChannelInitializer <TcpSocketChannel>(channel => { }))
                         .PreferredDnsResolutionFamily(family)
                         .Group(_serverGroup);

                s = sb.BindAsync(ep).Result;

                var cb = new ClientBootstrap()
                         .ChannelFactory(() => new TcpSocketChannel(family))
                         .Option(ChannelOption.TcpNodelay, true)
                         .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(100))
                         .PreferredDnsResolutionFamily(family)
                         .Handler(new ActionChannelInitializer <TcpSocketChannel>(channel => { }))
                         .Group(_clientGroup);

                var clientEp = s.LocalAddress;
                if (ip != null) // handle special case of 0.0.0.0, which clients can't connect to directly.
                {
                    if (ip.Address.Equals(IPAddress.Any))
                    {
                        clientEp = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)s.LocalAddress).Port);
                    }
                    if (ip.Address.Equals(IPAddress.IPv6Any))
                    {
                        clientEp = new IPEndPoint(IPAddress.IPv6Loopback, ((IPEndPoint)s.LocalAddress).Port);
                    }
                }

                c = cb.ConnectAsync(clientEp).Result;
                c.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(2)).Wait(20);

                return(c.IsOpen.Label("Channel should be open")
                       .And(c.IsActive).Label("Channel should be active")
                       .And(c.IsWritable).Label("Channel should be writable"));
            }
            finally
            {
                try
                {
                    c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                    s?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                }
                catch
                {
                }
            }
        }
Exemplo n.º 23
0
        public Property TcpServerSocketChannel_can_accept_connection_on_any_valid_Endpoint(EndPoint ep)
        {
            var ip = ep as IPEndPoint;
            var family = ep.BestAddressFamily();

            // TODO: remove this code once https://bugzilla.xamarin.com/show_bug.cgi?id=35536 is fixed

            if (IsMono && family == AddressFamily.InterNetworkV6 && ep is DnsEndPoint)
            {
                family = AddressFamily.InterNetwork;
            }

            IChannel s = null;
            IChannel c = null;
            try
            {
                var sb = new ServerBootstrap()
                    .ChannelFactory(() => new TcpServerSocketChannel(family))
                    .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { }))
                    .PreferredDnsResolutionFamily(family)
                    .Group(_serverGroup);

                s = sb.BindAsync(ep).Result;

                var cb = new ClientBootstrap()
                    .ChannelFactory(() => new TcpSocketChannel(family))
                    .Option(ChannelOption.TcpNodelay, true)
                    .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(100))
                    .PreferredDnsResolutionFamily(family)
                    .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel => { }))
                    .Group(_clientGroup);

                var clientEp = s.LocalAddress;
                if (ip != null) // handle special case of 0.0.0.0, which clients can't connect to directly.
                {
                    if (ip.Address.Equals(IPAddress.Any))
                        clientEp = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint) s.LocalAddress).Port);
                    if (ip.Address.Equals(IPAddress.IPv6Any))
                        clientEp = new IPEndPoint(IPAddress.IPv6Loopback, ((IPEndPoint) s.LocalAddress).Port);
                }

                c = cb.ConnectAsync(clientEp).Result;
                c.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(2)).Wait(20);

                return c.IsOpen.Label("Channel should be open")
                    .And(c.IsActive).Label("Channel should be active")
                    .And(c.IsWritable).Label("Channel should be writable");
            }
            finally
            {
                try
                {
                    c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                    s?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                }
                catch
                {
                }
            }
        }
Exemplo n.º 24
0
        public void TcpSocketChannel_can_connect_to_TcpServerSocketChannel()
        {
            IEventLoopGroup group1 = new MultithreadEventLoopGroup(2);
            IEventLoopGroup group2 = new MultithreadEventLoopGroup(2);

            var cb = new ClientBootstrap();
            var sb = new ServerBootstrap();
            var reads = 100;
            var resetEvent = new ManualResetEventSlim();

            cb.Group(group1)
                .Channel<TcpSocketChannel>()
                .Handler(
                    new ActionChannelInitializer<TcpSocketChannel>(
                        channel =>
                        {
                            channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                                .AddLast(new LengthFieldPrepender(4, false))
                                .AddLast(new IntCodec())
                                .AddLast(new TestHandler());
                        }));

            sb.Group(group2)
                .Channel<TcpServerSocketChannel>()
                .ChildHandler(
                    new ActionChannelInitializer<TcpSocketChannel>(
                        channel =>
                        {
                            channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                                .AddLast(new LengthFieldPrepender(4, false))
                                .AddLast(new IntCodec())
                                .AddLast(new ReadCountAwaiter(resetEvent, reads))
                                .AddLast(new TestHandler());
                        }));

            IChannel sc = null;
            IChannel cc = null;
            try
            {
                // Start server
                sc = sb.BindAsync(TEST_ADDRESS).Result;

                // Connect to the server
                cc = cb.ConnectAsync(sc.LocalAddress).Result;

                foreach (var read in Enumerable.Range(0, reads))
                {
                    cc.WriteAndFlushAsync(read);
                }
                Assert.True(resetEvent.Wait(15000));
            }
            finally
            {
                CloseChannel(cc);
                CloseChannel(sc);
                Task.WaitAll(group1.ShutdownGracefullyAsync(), group2.ShutdownGracefullyAsync());
            }
        }
Exemplo n.º 25
0
        public void LocalChannel_PeerClose_when_WritePromiseComplete_in_same_eventloop_should_still_preserve_order()
        {
            var cb = new ClientBootstrap();
            var sb = new ServerBootstrap();
            var messageLatch = new CountdownEvent(2);
            var data = Unpooled.WrappedBuffer(new byte[1024]);
            var serverLatch = new CountdownEvent(1);
            var serverChannelRef = new AtomicReference<IChannel>();

            try
            {
                cb.Group(_sharedGroup)
                    .Channel<LocalChannel>()
                    .Handler(new TestHandler());

                sb.Group(_sharedGroup)
                    .Channel<LocalServerChannel>()
                    .ChildHandler(new ActionChannelInitializer<LocalChannel>(channel =>
                    {
                        channel.Pipeline.AddLast(new ReadCountdown1(messageLatch, data));
                        serverChannelRef = channel;
                        serverLatch.Signal();
                    }));

                IChannel sc = null;
                IChannel cc = null;

                try
                {
                    // Start server
                    sc = sb.BindAsync(TEST_ADDRESS).Result;

                    // Connect to server
                    cc = cb.ConnectAsync(sc.LocalAddress).Result;
                    serverLatch.Wait(TimeSpan.FromSeconds(5));
                    Assert.True(serverLatch.IsSet);

                    var ccCpy = cc;

                    // Make sure a write operation is executed in the eventloop
                    cc.Pipeline.LastContext().Executor.Execute(() =>
                    {
                        ccCpy.WriteAndFlushAsync(data.Duplicate().Retain()).ContinueWith(tr =>
                        {
                            var severChannelCopy = serverChannelRef.Value;
                            severChannelCopy.CloseAsync();
                        });
                    });

                    Assert.True(messageLatch.Wait(TimeSpan.FromSeconds(5)));
                    Assert.False(cc.IsOpen);
                    Assert.False(serverChannelRef.Value.IsOpen);
                }
                finally
                {
                    CloseChannel(sc);
                    CloseChannel(cc);
                }
            }
            finally
            {
                data.Release();
            }
        }
Exemplo n.º 26
0
        public void LocalChannel_batch_read_should_not_NRE()
        {
            var cb = new ClientBootstrap();
            var sb = new ServerBootstrap();
            var reads = 100;
            var resetEvent = new ManualResetEventSlim();

            cb.Group(_group1)
                .Channel<LocalChannel>()
                .Handler(
                    new ActionChannelInitializer<LocalChannel>(
                        channel =>
                        {
                            channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                                .AddLast(new LengthFieldPrepender(4, false))
                                .AddLast(new TestHandler());
                        }));

            sb.Group(_group2)
                .Channel<LocalServerChannel>()
                .ChildHandler(
                    new ActionChannelInitializer<LocalChannel>(
                        channel =>
                        {
                            channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                                .AddLast(new LengthFieldPrepender(4, false))
                                .AddLast(new ReadCountAwaiter(resetEvent, reads))
                                .AddLast(new TestHandler());
                        }));

            IChannel sc = null;
            IChannel cc = null;

            try
            {
                // Start server
                sc = sb.BindAsync(TEST_ADDRESS).Result;

                // Connect to the server
                cc = cb.ConnectAsync(sc.LocalAddress).Result;

                foreach (var read in Enumerable.Range(0, reads))
                {
                    cc.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(read));
                }
                Assert.True(resetEvent.Wait(5000));
            }
            finally
            {
                CloseChannel(sc);
                CloseChannel(cc);
            }
        }
Exemplo n.º 27
0
        public void LocalChannel_write_when_WritePromiseComplete_should_still_preserve_order()
        {
            var cb = new ClientBootstrap();
            var sb = new ServerBootstrap();
            var messageLatch = new CountdownEvent(2);
            var data1 = Unpooled.WrappedBuffer(new byte[1024]);
            var data2 = Unpooled.WrappedBuffer(new byte[512]);

            try
            {
                cb.Group(_group1)
                    .Channel<LocalChannel>()
                    .Handler(new TestHandler());

                sb.Group(_group2)
                    .Channel<LocalServerChannel>()
                    .ChildHandler(new ReadCountdown2(messageLatch, data1, data2));

                IChannel sc = null;
                IChannel cc = null;

                try
                {
                    // Start server
                    sc = sb.BindAsync(TEST_ADDRESS).Result;

                    // Connect to server
                    cc = cb.ConnectAsync(sc.LocalAddress).Result;

                    var ccCpy = cc;

                    // Make sure a write operation is executed in the eventloop
                    cc.Pipeline.LastContext().Executor.Execute(() =>
                    {
                        Logger.Info("Writing message 1");
                        ccCpy.WriteAndFlushAsync(data1.Duplicate().Retain()).ContinueWith(tr =>
                        {
                            Logger.Info("Writing message 2");
                            ccCpy.WriteAndFlushAsync(data2.Duplicate().Retain());
                        });
                    });

                    Assert.True(messageLatch.Wait(TimeSpan.FromSeconds(5)));
                }
                finally
                {
                    CloseChannel(sc);
                    CloseChannel(cc);
                }
            }
            finally
            {
                data1.Release();
                data2.Release();
            }
        }
Exemplo n.º 28
0
        public void LocalServerChannel_should_be_able_to_close_channel_on_same_EventLoop()
        {
            var latch = new CountdownEvent(1);
            var sb = new ServerBootstrap();

            sb.Group(_group2).Channel<LocalServerChannel>().ChildHandler(new ReadHandler1(latch));

            IChannel sc = null;
            IChannel cc = null;

            try
            {
                sc = sb.BindAsync(TEST_ADDRESS).Result;

                var b = new ClientBootstrap()
                    .Group(_group2)
                    .Channel<LocalChannel>().Handler(new ReadHandler2());
                cc = b.ConnectAsync(sc.LocalAddress).Result;
                cc.WriteAndFlushAsync(new object());
                Assert.True(latch.Wait(TimeSpan.FromSeconds(5)));
            }
            finally
            {
                CloseChannel(cc);
                CloseChannel(sc);
            }
        }
Exemplo n.º 29
0
        public void LocalChannel_WriteAsync_should_fail_fast_on_closed_channel()
        {
            var cb = new ClientBootstrap();
            var sb = new ServerBootstrap();

            cb.Group(_group1).Channel<LocalChannel>().Handler(new TestHandler());

            sb.Group(_group2).Channel<LocalServerChannel>().ChildHandler(new ActionChannelInitializer<LocalChannel>(
                channel => { channel.Pipeline.AddLast(new TestHandler()); }));

            IChannel sc = null;
            IChannel cc = null;

            try
            {
                // Start server
                sc = sb.BindAsync(TEST_ADDRESS).Result;
                var latch = new CountdownEvent(1);

                // Connect to the server
                cc = cb.ConnectAsync(sc.LocalAddress).Result;

                // Close the channel and write something
                cc.CloseAsync().Wait();
                var ag =
                    Assert.Throws<AggregateException>(() => { cc.WriteAndFlushAsync(new object()).Wait(); }).Flatten();
                Assert.IsType<ClosedChannelException>(ag.InnerException);
            }
            finally
            {
                CloseChannel(cc);
                CloseChannel(sc);
            }
        }
Exemplo n.º 30
0
        public void LocalChannel_should_reuse_LocalAddress()
        {
            for (var i = 0; i < 2; i++)
            {
                var cb = new ClientBootstrap();
                var sb = new ServerBootstrap();

                cb.Group(_group1).Channel<LocalChannel>().Handler(new TestHandler());

                sb.Group(_group2).Channel<LocalServerChannel>().ChildHandler(new ActionChannelInitializer<LocalChannel>(
                    channel => { channel.Pipeline.AddLast(new TestHandler()); }));

                IChannel sc = null;
                IChannel cc = null;

                try
                {
                    // Start server
                    sc = sb.BindAsync(TEST_ADDRESS).Result;
                    var latch = new CountdownEvent(1);

                    // Connect to the server
                    cc = cb.ConnectAsync(sc.LocalAddress).Result;
                    var cCpy = cc;
                    cc.EventLoop.Execute(o =>
                    {
                        var c = (LocalChannel) o;
                        c.Pipeline.FireChannelRead("Hello, World");
                        latch.Signal();
                    }, cCpy);

                    latch.Wait(TimeSpan.FromSeconds(5));
                    Assert.True(latch.IsSet);

                    CloseChannel(cc);
                    CloseChannel(sc);
                    sc.CloseCompletion.Wait();

                    Assert.Null(LocalChannelRegistry.Get(TEST_ADDRESS));
                }
                finally
                {
                    CloseChannel(cc);
                    CloseChannel(sc);
                }
            }
        }
Exemplo n.º 31
0
        public void SetUp(BenchmarkContext context)
        {
            ClientGroup = new MultithreadEventLoopGroup(1);
            ServerGroup = new MultithreadEventLoopGroup(1);
            WorkerGroup = new MultithreadEventLoopGroup();


            var iso = Encoding.GetEncoding("ISO-8859-1");
            message = iso.GetBytes("ABC");

            // pre-allocate all messages
            foreach (var m in Enumerable.Range(0, WriteCount))
            {
                messages[m] = Unpooled.WrappedBuffer(message);
            }

            _inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName);
            _outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName);
            var counterHandler = new CounterHandlerInbound(_inboundThroughputCounter);
            _signal = new ManualResetEventSlimReadFinishedSignal(ResetEvent);

            var sb = new ServerBootstrap().Group(ServerGroup, WorkerGroup).Channel<TcpServerSocketChannel>()
                .ChildOption(ChannelOption.TcpNodelay, true)
                .ChildHandler(
                    new ActionChannelInitializer<TcpSocketChannel>(
                        channel =>
                        {
                            channel.Pipeline.AddLast(GetEncoder())
                                .AddLast(GetDecoder())
                                .AddLast(counterHandler)
                                .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter))
                                .AddLast(new ReadFinishedHandler(_signal, WriteCount));
                        }));

            var cb = new ClientBootstrap().Group(ClientGroup)
                .Option(ChannelOption.TcpNodelay, true)
                .Channel<TcpSocketChannel>().Handler(new ActionChannelInitializer<TcpSocketChannel>(
                    channel =>
                    {
                        channel.Pipeline.AddLast(GetEncoder()).AddLast(GetDecoder()).AddLast(counterHandler)
                            .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter));
                    }));

            // start server
            _serverChannel = sb.BindAsync(TEST_ADDRESS).Result;

            // connect to server
            _clientChannel = cb.ConnectAsync(_serverChannel.LocalAddress).Result;
            //_clientChannel.Configuration.AutoRead = false;
        }
Exemplo n.º 32
0
        public void LocalChannel_PeerClose_when_WritePromiseComplete_in_same_eventloop_should_still_preserve_order()
        {
            var cb               = new ClientBootstrap();
            var sb               = new ServerBootstrap();
            var messageLatch     = new CountdownEvent(2);
            var data             = Unpooled.WrappedBuffer(new byte[1024]);
            var serverLatch      = new CountdownEvent(1);
            var serverChannelRef = new AtomicReference <IChannel>();

            try
            {
                cb.Group(_sharedGroup)
                .Channel <LocalChannel>()
                .Handler(new TestHandler());

                sb.Group(_sharedGroup)
                .Channel <LocalServerChannel>()
                .ChildHandler(new ActionChannelInitializer <LocalChannel>(channel =>
                {
                    channel.Pipeline.AddLast(new ReadCountdown1(messageLatch, data));
                    serverChannelRef = channel;
                    serverLatch.Signal();
                }));

                IChannel sc = null;
                IChannel cc = null;

                try
                {
                    // Start server
                    sc = sb.BindAsync(TEST_ADDRESS).Result;

                    // Connect to server
                    cc = cb.ConnectAsync(sc.LocalAddress).Result;
                    serverLatch.Wait(TimeSpan.FromSeconds(5));
                    Assert.True(serverLatch.IsSet);

                    var ccCpy = cc;

                    // Make sure a write operation is executed in the eventloop
                    cc.Pipeline.LastContext().Executor.Execute(() =>
                    {
                        ccCpy.WriteAndFlushAsync(data.Duplicate().Retain()).ContinueWith(tr =>
                        {
                            var severChannelCopy = serverChannelRef.Value;
                            severChannelCopy.CloseAsync();
                        });
                    });

                    Assert.True(messageLatch.Wait(TimeSpan.FromSeconds(5)));
                    Assert.False(cc.IsOpen);
                    Assert.False(serverChannelRef.Value.IsOpen);
                }
                finally
                {
                    CloseChannel(sc);
                    CloseChannel(cc);
                }
            }
            finally
            {
                data.Release();
            }
        }
        public void SetUp(BenchmarkContext context)
        {
            ClientGroup = new MultithreadEventLoopGroup(Environment.ProcessorCount / 2);
            ServerGroup = new MultithreadEventLoopGroup(1);
            WorkerGroup = new MultithreadEventLoopGroup(Environment.ProcessorCount / 2);

            _shutdownBenchmark = new CancellationTokenSource();
            _clientChannels    = new ConcurrentBag <IChannel>();

            _inboundThroughputCounter  = context.GetCounter(InboundThroughputCounterName);
            _outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName);
            _clientConnectedCounter    = context.GetCounter(ClientConnectCounterName);
            _errorCounter = context.GetCounter(ErrorCounterName);

            _signal = new ManualResetEventSlimReadFinishedSignal(ResetEvent);

            var sb = new ServerBootstrap().Group(ServerGroup, WorkerGroup).Channel <TcpServerSocketChannel>()
                     .ChildOption(ChannelOption.TcpNodelay, true)
                     .ChildHandler(new ActionChannelInitializer <TcpSocketChannel>(channel =>
            {
                channel.Pipeline.AddLast(GetEncoder())
                .AddLast(GetDecoder())
                .AddLast(new IntCodec(true))
                .AddLast(new CounterHandlerInbound(_inboundThroughputCounter))
                .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter))
                .AddLast(new ErrorCounterHandler(_errorCounter));
            }));

            ClientBootstrap = new ClientBootstrap().Group(ClientGroup)
                              .Option(ChannelOption.TcpNodelay, true)
                              .Channel <TcpSocketChannel>().Handler(new ActionChannelInitializer <TcpSocketChannel>(
                                                                        channel =>
            {
                channel.Pipeline.AddLast(GetEncoder())
                .AddLast(GetDecoder())
                .AddLast(new IntCodec(true))
                .AddLast(new CounterHandlerInbound(_inboundThroughputCounter))
                .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter))
                .AddLast(new ErrorCounterHandler(_errorCounter));
            }));

            var token = _shutdownBenchmark.Token;

            _eventLoop = () =>
            {
                while (!token.IsCancellationRequested)
                {
                    foreach (var channel in _clientChannels)
                    {
                        // unrolling a loop
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.Flush();
                    }

                    // sleep for a tiny bit, then get going again
                    Thread.Sleep(40);
                }
            };

            // start server
            _serverChannel = sb.BindAsync(TEST_ADDRESS).Result;

            // connect to server with 1 client initially
            _clientChannels.Add(ClientBootstrap.ConnectAsync(_serverChannel.LocalAddress).Result);
        }
Exemplo n.º 34
0
        public void SetUp(BenchmarkContext context)
        {
            ClientGroup = new MultithreadEventLoopGroup(1);
            ServerGroup = new MultithreadEventLoopGroup(2);

            var iso = Encoding.GetEncoding("ISO-8859-1");
            message = iso.GetBytes("ABC");

            _inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName);
            _outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName);
            var counterHandler = new CounterHandlerInbound(_inboundThroughputCounter);
            _signal = new SimpleReadFinishedSignal();

            var sb = new ServerBootstrap().Group(ServerGroup).Channel<LocalServerChannel>()
                .ChildHandler(
                    new ActionChannelInitializer<LocalChannel>(
                        channel =>
                        {
                            channel.Pipeline.AddLast(GetEncoder())
                                .AddLast(GetDecoder())
                                .AddLast(counterHandler)
                                .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter))
                                .AddLast(new ReadFinishedHandler(_signal, WriteCount));
                        }));

            var cb =
                new ClientBootstrap().Group(ClientGroup)
                    .Channel<LocalChannel>()
                    .Handler(new ActionChannelInitializer<LocalChannel>(
                        channel =>
                        {
                            channel.Pipeline.AddLast(GetEncoder()).AddLast(GetDecoder()).AddLast(counterHandler)
                                .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter));
                        }));

            // start server
            _serverChannel = sb.BindAsync(TEST_ADDRESS).Result;

            // connect to server
            _clientChannel = cb.ConnectAsync(_serverChannel.LocalAddress).Result;
        }
        public void SetUp(BenchmarkContext context)
        {
            ClientGroup = new MultithreadEventLoopGroup(Environment.ProcessorCount/2);
            ServerGroup = new MultithreadEventLoopGroup(1);
            WorkerGroup = new MultithreadEventLoopGroup(Environment.ProcessorCount/2);

            _shutdownBenchmark = new CancellationTokenSource();
            _clientChannels = new ConcurrentBag<IChannel>();

            _inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName);
            _outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName);
            _clientConnectedCounter = context.GetCounter(ClientConnectCounterName);
            _errorCounter = context.GetCounter(ErrorCounterName);

            _signal = new ManualResetEventSlimReadFinishedSignal(ResetEvent);

            var sb = new ServerBootstrap().Group(ServerGroup, WorkerGroup).Channel<TcpServerSocketChannel>()
                .ChildOption(ChannelOption.TcpNodelay, true)
                .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel =>
                {
                    channel.Pipeline.AddLast(GetEncoder())
                        .AddLast(GetDecoder())
                        .AddLast(new IntCodec(true))
                        .AddLast(new CounterHandlerInbound(_inboundThroughputCounter))
                        .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter))
                        .AddLast(new ErrorCounterHandler(_errorCounter));
                }));

            ClientBootstrap = new ClientBootstrap().Group(ClientGroup)
                .Option(ChannelOption.TcpNodelay, true)
                .Channel<TcpSocketChannel>().Handler(new ActionChannelInitializer<TcpSocketChannel>(
                    channel =>
                    {
                        channel.Pipeline.AddLast(GetEncoder())
                            .AddLast(GetDecoder())
                            .AddLast(new IntCodec(true))
                            .AddLast(new CounterHandlerInbound(_inboundThroughputCounter))
                            .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter))
                            .AddLast(new ErrorCounterHandler(_errorCounter));
                    }));

            var token = _shutdownBenchmark.Token;
            _eventLoop = () =>
            {
                while (!token.IsCancellationRequested)
                {
                    foreach (var channel in _clientChannels)
                    {
                        // unrolling a loop
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.WriteAsync(ThreadLocalRandom.Current.Next());
                        channel.Flush();
                    }

                    // sleep for a tiny bit, then get going again
                    Thread.Sleep(40);
                }
            };

            // start server
            _serverChannel = sb.BindAsync(TEST_ADDRESS).Result;

            // connect to server with 1 client initially
            _clientChannels.Add(ClientBootstrap.ConnectAsync(_serverChannel.LocalAddress).Result);
        }
Exemplo n.º 36
0
        public void LocalChannel_writes_to_server_should_be_read_by_LocalChannel()
        {
            var cb = new ClientBootstrap();
            var sb = new ServerBootstrap();
            var reads = new[] {-11, 2, 9, 13, 1013, 1, 4};
            var resetEvent = new ManualResetEventSlim();
            var accumulatedReads = new List<int>();

            cb.Group(_group1)
                .Channel<LocalChannel>()
                .Handler(
                    new ActionChannelInitializer<LocalChannel>(
                        channel =>
                        {
                            channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                                .AddLast(new LengthFieldPrepender(4, false))
                                .AddLast(new IntCodec());
                        }));

            sb.Group(_group2)
                .Channel<LocalServerChannel>()
                .ChildHandler(
                    new ActionChannelInitializer<LocalChannel>(
                        channel =>
                        {
                            channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4))
                                .AddLast(new LengthFieldPrepender(4, false))
                                .AddLast(new IntCodec())
                                .AddLast(new ReadAssertHandler(accumulatedReads, resetEvent, reads));
                        }));

            IChannel sc = null;
            IChannel cc = null;

            try
            {
                // Start server
                sc = sb.BindAsync(TEST_ADDRESS).Result;

                // Connect to the server
                cc = cb.ConnectAsync(sc.LocalAddress).Result;

                foreach (var read in reads)
                {
                    cc.WriteAsync(read);
                }
                cc.Flush();
                resetEvent.Wait(200);
                Assert.Equal(reads, accumulatedReads);
            }
            finally
            {
                CloseChannel(sc);
                CloseChannel(cc);
            }
        }
Exemplo n.º 37
0
        public static Task<IChannel> CreateConnection(Role role, IPEndPoint socketAddress, int poolSize, IChannelHandler upstreamHandler)
        {
            if (role == Role.Client)
            {
                var connection = new ClientBootstrap()
                    .ChannelFactory(() => new TcpSocketChannel(socketAddress.AddressFamily))
                    .Option(ChannelOption.TcpNodelay, true)
                    .Group(GetClientWorkerPool(poolSize))
                    .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel =>
                    {
                        ApplyChannelPipeline(channel, upstreamHandler);
                    }));

                return connection.ConnectAsync(socketAddress);
            }
            else //server
            {
                var connection = new ServerBootstrap()
                    .Group(GetServerPool(poolSize), GetServerWorkerPool(poolSize))
                    .ChannelFactory(() => new TcpServerSocketChannel(socketAddress.AddressFamily))
                    .ChildOption(ChannelOption.TcpNodelay, true)
                    .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel =>
                    {
                        ApplyChannelPipeline(channel, upstreamHandler);
                    }));
                return connection.BindAsync(socketAddress);
            }
        }
Exemplo n.º 38
0
        public void TcpSocketServerChannel_can_be_connected_to_on_any_aliased_Endpoint(IpMapping actual,
            IpMapping alias, AddressFamily family)
        {
            var inboundActual = MappingToEndpoint(actual);
            var inboundAlias = MappingToEndpoint(alias);
            var isIp = inboundAlias is IPEndPoint;

            if (IsMono && family == AddressFamily.InterNetworkV6)
            {
                Assert.True(true, "Mono currently does not support IPV6 in DNS resolution");
                return;
            }


            IChannel s = null;
            IChannel c = null;
            try
            {
                var sb = new ServerBootstrap()
                    .ChannelFactory(() => new TcpServerSocketChannel())
                    .PreferredDnsResolutionFamily(family)
                    .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { }))
                    .Group(_serverGroup);

                s = sb.BindAsync(inboundActual).Result;


                var cb = new ClientBootstrap()
                    .ChannelFactory(() => new TcpSocketChannel())
                    .Option(ChannelOption.TcpNodelay, true)
                    .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(100))
                    .PreferredDnsResolutionFamily(family)
                    .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel => { }))
                    .Group(_clientGroup);

                EndPoint clientEp = isIp
                    ? new IPEndPoint(((IPEndPoint) inboundAlias).Address, ((IPEndPoint) s.LocalAddress).Port)
                    : (EndPoint) new DnsEndPoint(((DnsEndPoint) inboundAlias).Host, ((IPEndPoint) s.LocalAddress).Port);

                c = cb.ConnectAsync(clientEp).Result;
                c.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(2)).Wait(20);

                Assert.True(c.IsOpen);
                Assert.True(c.IsActive);
                Assert.True(c.IsWritable);
            }
            finally
            {
                try
                {
                    c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                    s?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
                }
                catch
                {
                }
            }
        }