Esempio n. 1
0
        public Entry()
        {
            Log           = null;
            _loopContinue = true;

            rx = new Regex(@"([\d.]+):(\d+)",
                           RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Compiled);

            try
            {
                var clientBootstrap = new ClientBootstrap()
                                      .SetTransport(TransportType.Udp)
                                      .OnConnect(ConnectionEstablishedCallback)
                                      .OnReceive(ReceivedDataCallback)
                                      .OnDisconnect(ConnectionTerminatedCallback)
                                      .OnError(ConnectionOnOnError);
                _connectionFactory = clientBootstrap.Build();
            }
            catch (Exception)
            {
                throw;
            }
            _nodeDictionary       = new Dictionary <string, INode>();
            _connectionDictionary = new Dictionary <string, IConnection>();
        }
Esempio n. 2
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);
            }
        }
Esempio n. 3
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);
            }
        }
Esempio n. 4
0
        private static void Main(string[] args)
        {
            Console.WriteLine("We're going to write a ton of data to the console. 100k iterations.");
            Console.WriteLine("Going!");

            var remote = Node.Loopback(11010);
            var client =
                new ClientBootstrap().SetTransport(TransportType.Udp)
                .SetEncoder(new NoOpEncoder())
                .SetDecoder(new NoOpDecoder()).Build().NewConnection(Node.Any(), remote);

            client.Open();
            var bytes = Encoding.UTF8.GetBytes("THIS IS OUR TEST PAYLOAD");

            var stopwatch = Stopwatch.StartNew();
            var i         = 0;

            while (i < 100000)
            {
                client.Send(bytes, 0, bytes.Length, remote);
                i++;
            }
            Console.WriteLine("Done queuing messages... waiting for queue to drain");
            while (client.MessagesInSendQueue > 0)
            {
                Thread.Sleep(10);
            }
            Console.WriteLine("Done, press any key to exit");
            stopwatch.Stop();
            Console.WriteLine("Took {0} seconds to complete", stopwatch.Elapsed.TotalSeconds);
            Console.ReadKey();
        }
Esempio n. 5
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));
            }
        }
            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);
            }
Esempio n. 7
0
        static void Main(string[] args)
        {
            ParseArgs(args);
            InitLogging();
            InitOutput();

            var tlsOptions = InitTls();
            var elg        = new EventLoopGroup();
            var client     = new ClientBootstrap(elg);

            try
            {
                var connectionTask = InitHttp(client, tlsOptions);
                var streamTask     = InitStream(connectionTask.Result);
                var result         = streamTask.Result;
                Console.WriteLine("Completed with code {0}", result.ErrorCode);
            }
            catch (AggregateException agg) // thrown by TaskCompletionSource
            {
                Console.Write("Operation failed: ");
                foreach (var ex in agg.Flatten().InnerExceptions)
                {
                    Console.WriteLine(ex.Message);
                }
                Environment.Exit(-1);
            }
            finally
            {
                if (ctx.OutputStream != null)
                {
                    ctx.OutputStream.Flush();
                    ctx.OutputStream.Close();
                }
            }
        }
Esempio n. 8
0
 public static RemoteConnection CreateConnection(Role role, INode socketAddress, int poolSize, IHeliosConnectionHandler upstreamHandler)
 {
     if (role == Role.Client)
     {
         var connection = new ClientBootstrap().SetTransport(TransportType.Tcp)
                          .SetOption("TcpNoDelay", true)
                          .SetEncoder(Encoders.DefaultEncoder) //LengthFieldPrepender
                          .SetDecoder(Encoders.DefaultDecoder) //LengthFieldFrameBasedDecoder
                          .WorkerThreads(poolSize).Build().NewConnection(socketAddress);
         var remoteConnection = new RemoteConnection(connection, upstreamHandler);
         remoteConnection.Open();
         return(remoteConnection);
     }
     else //server
     {
         var connection = new ServerBootstrap().SetTransport(TransportType.Tcp)
                          .SetOption("TcpNoDelay", true)
                          .SetEncoder(Encoders.DefaultEncoder) //LengthFieldPrepender
                          .SetDecoder(Encoders.DefaultDecoder) //LengthFieldFrameBasedDecoder
                          .WorkerThreads(poolSize).Build().NewConnection(socketAddress);
         var remoteConnection = new RemoteConnection(connection, upstreamHandler);
         remoteConnection.Open();
         return(remoteConnection);
     }
 }
Esempio n. 9
0
 public void ClientBootstrapLifetime()
 {
     var elg          = new EventLoopGroup(1);
     var hostResolver = new DefaultHostResolver(elg);
     var bootstrap    = new ClientBootstrap(elg, hostResolver);
     // When these go out of scope, the native handle will be released
 }
Esempio n. 10
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));
        }
        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
                {
                }
            }
        }
Esempio n. 12
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());
            }
        }
Esempio n. 13
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());
            }
        }
Esempio n. 14
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
                {
                }
            }
        }
Esempio n. 15
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);
            }
        }
Esempio n. 16
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();
            }
        }
Esempio n. 17
0
        public override void Start()
        {
            _channels = new DefaultChannelGroup();

            // Start client bootstrap
            _clientBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newSingleThreadExecutor(daemon("Cluster client boss", _monitor)), Executors.newFixedThreadPool(2, daemon("Cluster client worker", _monitor)), 2));
            _clientBootstrap.setOption("tcpNoDelay", true);
            _clientBootstrap.PipelineFactory = new NetworkNodePipelineFactory(this);

            _msgLog.debug("Started NetworkSender for " + ToString(_config));
        }
Esempio n. 18
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
                {
                }
            }
        }
Esempio n. 19
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);
            }
        }
Esempio n. 20
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);
            }
        }
        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
                {
                }
            }
        }
Esempio n. 22
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;
        }
Esempio n. 23
0
        public void TestClient()
        {
            var bootstrap = new ClientBootstrap();
            var session   = bootstrap.AddressAndPort("127.0.0.1", 8888)
                            .Session <TcpSession>()
                            .Init(_session =>
            {
                _session.Pipeline.AddOutbound("Test", new TestOutboundHandler());
            })
                            .Connect();

            Console.WriteLine(1000);
            session.Send(1000);
        }
Esempio n. 24
0
        public void UdpConnection_should_bind_to_outbound_ephemeral_port()
        {
            var serverAddress = NodeBuilder.BuildNode().Host(IPAddress.Loopback).WithPort(13171);
            var server        =
                new ServerBootstrap().SetTransport(TransportType.Udp).Build().NewReactor(serverAddress);
            var connection = new ClientBootstrap().SetTransport(TransportType.Udp)
                             .Build()
                             .NewConnection(Node.Loopback(), serverAddress);

            server.Start();
            connection.Open();
            Assert.NotEqual(0, connection.Local.Port);
            connection.Close();
            server.Stop();
        }
Esempio n. 25
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);
                }
            }
        }
Esempio n. 26
0
        static Task <HttpClientConnection> InitHttp(ClientBootstrap client, TlsConnectionOptions tlsOptions)
        {
            var options = new HttpClientConnectionOptions();

            options.ClientBootstrap      = client;
            options.TlsConnectionOptions = tlsOptions;
            options.HostName             = ctx.Uri.Host;
            options.Port = (UInt16)ctx.Uri.Port;
            options.ConnectionShutdown += OnConnectionShutdown;
            if (ctx.ConnectTimeoutMs != 0)
            {
                var socketOptions = new SocketOptions();
                socketOptions.ConnectTimeoutMs = ctx.ConnectTimeoutMs;
                options.SocketOptions          = socketOptions;
            }
            return(HttpClientConnection.NewConnection(options));
        }
Esempio n. 27
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);
            }
        }
        public TcpSocketChannelAndReactorCompatSpecs()
        {
            _clientGroup = new MultithreadEventLoopGroup(1);
            _serverBootstrap = new ServerBootstrap()
                .SetTransport(TransportType.Tcp)
                .SetDecoder(new LengthFieldFrameBasedDecoder(int.MaxValue, 0, 4, 0, 4))
                .SetEncoder(new LengthFieldPrepender(4, false)).Build();

            _clientBootstrap = new ClientBootstrap()
                .Channel<TcpSocketChannel>()
                .Group(_clientGroup)
                .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel =>
                {
                    channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4, true))
                        .AddLast(new HeliosBackwardsCompatabilityLengthFramePrepender(4, false))
                        .AddLast(new ReadRecorderHandler(_received, _resetEvent, ReadCount));
                }));
        }
        public TcpSocketChannelAndReactorCompatSpecs()
        {
            _clientGroup     = new MultithreadEventLoopGroup(1);
            _serverBootstrap = new ServerBootstrap()
                               .SetTransport(TransportType.Tcp)
                               .SetDecoder(new LengthFieldFrameBasedDecoder(int.MaxValue, 0, 4, 0, 4))
                               .SetEncoder(new LengthFieldPrepender(4, false)).Build();

            _clientBootstrap = new ClientBootstrap()
                               .Channel <TcpSocketChannel>()
                               .Group(_clientGroup)
                               .Handler(new ActionChannelInitializer <TcpSocketChannel>(channel =>
            {
                channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4, true))
                .AddLast(new HeliosBackwardsCompatabilityLengthFramePrepender(4, false))
                .AddLast(new ReadRecorderHandler(_received, _resetEvent, ReadCount));
            }));
        }
Esempio n. 30
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;
        }
Esempio n. 31
0
        /// <summary>
        /// Internal factory used for creating new outbound connection transports
        /// </summary>
        /// <param name="remoteAddres">TBD</param>
        /// <exception cref="NotSupportedException">TBD</exception>
        /// <returns>TBD</returns>
        protected ClientBootstrap ClientFactory(Address remoteAddres)
        {
            if (InternalTransport == TransportType.Tcp)
            {
                var addressFamily = Settings.DnsUseIpv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;

                var client = new ClientBootstrap()
                             .Group(_clientEventLoopGroup)
                             .Option(ChannelOption.SoReuseaddr, Settings.TcpReuseAddr)
                             .Option(ChannelOption.SoKeepalive, Settings.TcpKeepAlive)
                             .Option(ChannelOption.TcpNodelay, Settings.TcpNoDelay)
                             .Option(ChannelOption.ConnectTimeout, Settings.ConnectTimeout)
                             .Option(ChannelOption.AutoRead, false)
                             .PreferredDnsResolutionFamily(addressFamily)
                             .ChannelFactory(() => Settings.EnforceIpFamily ?
                                             new TcpSocketChannel(addressFamily) :
                                             new TcpSocketChannel())
                             .Handler(
                    new ActionChannelInitializer <TcpSocketChannel>(
                        channel => SetClientPipeline(channel, remoteAddres)));

                if (Settings.ReceiveBufferSize != null)
                {
                    client.Option(ChannelOption.SoRcvbuf, (int)(Settings.ReceiveBufferSize));
                }
                if (Settings.SendBufferSize != null)
                {
                    client.Option(ChannelOption.SoSndbuf, (int)(Settings.SendBufferSize));
                }
                if (Settings.WriteBufferHighWaterMark != null)
                {
                    client.Option(ChannelOption.WriteBufferHighWaterMark, (int)(Settings.WriteBufferHighWaterMark));
                }
                if (Settings.WriteBufferLowWaterMark != null)
                {
                    client.Option(ChannelOption.WriteBufferLowWaterMark, (int)(Settings.WriteBufferLowWaterMark));
                }

                return(client);
            }

            throw new NotSupportedException("UDP is not supported");
        }
Esempio n. 32
0
        public void RunClient()
        {
            var ClientGroup    = new MultithreadEventLoopGroup(1);
            var counterHandler = new ClientCounterHandlerInbound();

            clientBootstrap = new ClientBootstrap().Group(ClientGroup)
                              .Option(ChannelOption.TcpNodelay, true)
                              .Channel <TcpSocketChannel>().Handler(new ActionChannelInitializer <TcpSocketChannel>(
                                                                        channel =>
            {
                channel.Pipeline
                .AddLast(new LengthFieldPrepender(4, false))
                .AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4))
                .AddLast(counterHandler);
            }));

            var _host = _serverChannel.LocalAddress.ToString();

            Node.ClustersNode.AddNodeDic(new Node.ClustersNodeSetting()
            {
                channel          = null,
                ConnectionStatus = true,
                master           = true,
                host             = _host,
                me = true,
            });

            var _node = ServerConfSetting.serverSettingClusters_Node_Model
                        .node.Where(x => x.ip.ToString() != _host).ToList();

            foreach (var item in _node)
            {
                Node.ClustersNode.AddNodeDic(new Node.ClustersNodeSetting()
                {
                    channel          = null,
                    ConnectionStatus = false,
                    master           = item.master,
                    host             = item.ip,
                    me = false,
                });
            }
        }
Esempio n. 33
0
        /// <summary>开始客户端
        ///
        /// </summary>
        public static void StartClient()
        {
            var       host = IPAddress.Loopback;
            const int port = 9991;
            var       connectionFactory = new ClientBootstrap().SetTransport(TransportType.Tcp).Build();

            //New一个Client
            _client = connectionFactory.NewConnection(Node.Empty(), NodeBuilder.BuildNode().Host(host).WithPort(port));
            _client.OnConnection += (address, connection) =>
            {
                connection.BeginReceive(Received);
            };
            _client.OnDisconnection += (address, reason) => { };
            //建立连接
            _client.Open();
            //加入服务端组
            Join();
            //等待输入
            //WaitInput();
        }
Esempio n. 34
0
        public override void Start()
        {
            _bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(newCachedThreadPool(daemon(this.GetType().Name + "-boss@" + _destination)), newCachedThreadPool(daemon(this.GetType().Name + "-worker@" + _destination))));
            _bootstrap.PipelineFactory = this;

            _channelPool = new ResourcePoolAnonymousInnerClass(this, _maxUnusedChannels);

            /*
             * This is here to couple the channel releasing to Response.close() itself and not
             * to TransactionStream.close() as it is implemented here. The reason is that a Response
             * that is returned without a TransactionStream will still hold the channel and should
             * release it eventually. Also, logically, closing the channel is not dependent on the
             * TransactionStream.
             */
            _resourcePoolReleaser = () =>
            {
                if (_channelPool != null)
                {
                    _channelPool.release();
                }
            };
        }
Esempio n. 35
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 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
                {
                }
            }
        }
        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
                {
                }
            }
        }
Esempio n. 38
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);
            }
        }
Esempio n. 39
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);
            }
        }
Esempio n. 40
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();
            }
        }
Esempio n. 41
0
        /// <summary>
        /// Internal factory used for creating new outbound connection transports
        /// </summary>
        protected ClientBootstrap ClientFactory(Address remoteAddres)
        {
            if (InternalTransport == TransportType.Tcp)
            {
                var addressFamily = Settings.DnsUseIpv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;

                var client = new ClientBootstrap()
                    .Group(_clientEventLoopGroup)
                    .Option(ChannelOption.SoReuseaddr, Settings.TcpReuseAddr)
                    .Option(ChannelOption.SoKeepalive, Settings.TcpKeepAlive)
                    .Option(ChannelOption.TcpNodelay, Settings.TcpNoDelay)
                    .Option(ChannelOption.ConnectTimeout, Settings.ConnectTimeout)
                    .Option(ChannelOption.AutoRead, false)
                    .PreferredDnsResolutionFamily(addressFamily)
                    .ChannelFactory(() => Settings.EnforceIpFamily ? 
                                        new TcpSocketChannel(addressFamily):
                                        new TcpSocketChannel())
                    .Handler(
                        new ActionChannelInitializer<TcpSocketChannel>(
                            channel => SetClientPipeline(channel, remoteAddres)));

                if (Settings.ReceiveBufferSize != null) client.Option(ChannelOption.SoRcvbuf, (int)(Settings.ReceiveBufferSize));
                if (Settings.SendBufferSize != null) client.Option(ChannelOption.SoSndbuf, (int)(Settings.SendBufferSize));
                if (Settings.WriteBufferHighWaterMark != null) client.Option(ChannelOption.WriteBufferHighWaterMark, (int)(Settings.WriteBufferHighWaterMark));
                if (Settings.WriteBufferLowWaterMark != null) client.Option(ChannelOption.WriteBufferLowWaterMark, (int)(Settings.WriteBufferLowWaterMark));

                return client;
            }

            throw new NotSupportedException("UDP is not supported");
        }
Esempio n. 42
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();
            }
        }
Esempio n. 43
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);
            }
        }
Esempio n. 44
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);
            }
        }
Esempio n. 45
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);
                }
            }
        }
Esempio n. 46
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;
        }
Esempio n. 47
0
        public void LocalChannel_should_not_fire_channel_active_before_connecting()
        {
            var cb = new ClientBootstrap();
            var sb = new ServerBootstrap();

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

            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;

                cc = cb.Register().Result;

                var promise = new TaskCompletionSource();
                var assertPromise = new TaskCompletionSource();

                cc.Pipeline.AddLast(new PromiseAssertHandler(promise, assertPromise));

                // Connect to the server
                cc.ConnectAsync(sc.LocalAddress).Wait();

                assertPromise.Task.Wait();
                Assert.True(promise.Task.IsCompleted);
            }
            finally
            {
                CloseChannel(cc);
                CloseChannel(sc);
            }
        }
        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);
        }