Esempio n. 1
0
        static async Task RunServerAsync()
        {
            Console.WriteLine("Gateway Start, ThreadName=" + System.Threading.Thread.CurrentThread.ManagedThreadId);

            var bossGroup = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                    .Group(bossGroup, workerGroup)
                    .Channel<TcpServerSocketChannel>()
                    .Option(ChannelOption.SoBacklog, 100)
                    .Handler(new LoggingHandler(LogLevel.INFO))
                    .ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
                    {
                        IChannelPipeline pipeline = channel.Pipeline;
                        pipeline.AddLast(new LengthFieldPrepender(2));
                        pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
                        pipeline.AddLast(new GatewayHandler());
                    }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(GatewaySettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
        public async Task StartAsync(EndPoint endPoint)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
                _logger.LogDebug($"准备启动服务主机,监听地址:{endPoint}。");

            var bossGroup = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();
            var bootstrap = new ServerBootstrap();
            bootstrap
                .Group(bossGroup, workerGroup)
                .Channel<TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
                {
                    var pipeline = channel.Pipeline;
                    pipeline.AddLast(new LengthFieldPrepender(4));
                    pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));
                    pipeline.AddLast(new TransportMessageChannelHandlerAdapter(_transportMessageDecoder));
                    pipeline.AddLast(new ServerHandler((contenxt, message) =>
                    {
                        var sender = new DotNettyServerMessageSender(_transportMessageEncoder, contenxt);
                        OnReceived(sender, message);
                    }, _logger));
                }));
            _channel = await bootstrap.BindAsync(endPoint);

            if (_logger.IsEnabled(LogLevel.Debug))
                _logger.LogDebug($"服务主机启动成功,监听地址:{endPoint}。");
        }
Esempio n. 3
0
        public void ServerBootrap_must_support_BindAsync_on_DnsEndpoints_for_SocketChannels()
        {
            var sb = new ServerBootstrap()
                .Channel<TcpServerSocketChannel>()
                .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { }))
                .Group(_serverGroup);

            var c = sb.BindAsync(new DnsEndPoint("localhost", 0)).Result;
        }
Esempio n. 4
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. 6
0
        public void TcpSocketChannel_Flush_should_not_be_reentrant_after_Close()
        {
            // Skip for Mono due to Code Contracts assertions not working properly there
            if (MonotonicClock.IsMono) return;

            var eventLoopGroup = new MultithreadEventLoopGroup(1);
            try
            {
                var futures = new ConcurrentQueue<Task>();
                var sb = new ServerBootstrap();
                sb.Group(eventLoopGroup).Channel<TcpServerSocketChannel>().ChildOption(ChannelOption.SoSndbuf, 1024)
                    .ChildHandler(new ChannelFlushCloseHandler(futures));

                var address = (IPEndPoint) sb.BindAsync(IPAddress.IPv6Loopback, 0).Result.LocalAddress;
                var s = new System.Net.Sockets.Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                s.Connect(address.Address, address.Port);

                var inputStream = new NetworkStream(s, true);
                var buf = new byte[8192];
                while (true)
                {
                    var readBytes = inputStream.Read(buf, 0, 8192);
                    if (readBytes == 0)
                    {
                        break;
                    }

                    // Wait a little bit so that the write attempts are split into multiple flush attempts.
                    Thread.Sleep(10);
                }

                s.Close();

                Assert.Equal(3, futures.Count);
                Task future1, future2, future3;
                futures.TryDequeue(out future1);
                futures.TryDequeue(out future2);
                futures.TryDequeue(out future3);
                Assert.True(future1.IsCompleted);
                Assert.False(future1.IsFaulted || future1.IsCanceled);
                Assert.True(future2.IsFaulted || future2.IsCanceled);
                Assert.IsType<ClosedChannelException>(future2.Exception.InnerException);
                Assert.True(future3.IsFaulted || future3.IsCanceled);
                Assert.IsType<ClosedChannelException>(future3.Exception.InnerException);
            }
            finally
            {
                eventLoopGroup.ShutdownGracefullyAsync();
            }
        }
Esempio n. 7
0
        static async Task RunServerAsync()
        {
            var eventListener = new ObservableEventListener();
            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);

            var bossGroup = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();
            X509Certificate2 tlsCertificate = null;
            if (EchoServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password");
            }
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                    .Group(bossGroup, workerGroup)
                    .Channel<TcpServerSocketChannel>()
                    .Option(ChannelOption.SoBacklog, 100)
                    .Handler(new LoggingHandler(LogLevel.INFO))
                    .ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
                    {
                        IChannelPipeline pipeline = channel.Pipeline;
                        if (tlsCertificate != null)
                        {
                            pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                        }
                        pipeline.AddLast(new LengthFieldPrepender(2));
                        pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                        pipeline.AddLast(new EchoServerHandler());
                    }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(EchoServerSettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
                eventListener.Dispose();
            }
        }
Esempio n. 8
0
        public async Task Run()
        {
            MultithreadEventLoopGroup bossGroup   = new MultithreadEventLoopGroup();
            MultithreadEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            try
            {
                ServerBootstrap b = new ServerBootstrap();
                b.Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    pipeline.AddLast("decoder", new StringDecoder());
                    pipeline.AddLast("encoder", new StringEncoder());
                    pipeline.AddLast("handler", new StringHandler());

                    Log.Info("initChannel:" + channel.RemoteAddress);
                }))
                .Option(ChannelOption.SoBacklog, 128)
                .ChildOption(ChannelOption.SoKeepalive, true);

                Log.Info("tcp server start......");

                IChannel f = await b.BindAsync(port);

                await f.CloseCompletion;
            }
            catch (Exception ex)
            {
                Log.Error("tcp server start error.");
            }
            finally
            {
                await workerGroup.ShutdownGracefullyAsync();

                await bossGroup.ShutdownGracefullyAsync();

                Log.Info("tcp server close");
            }
        }
Esempio n. 9
0
        public async Task TestFlushInWritabilityChanged()
        {
            LocalAddress addr = new LocalAddress("testFlushInWritabilityChanged");

            ServerBootstrap sb = GetLocalServerBootstrap();
            await sb.BindAsync(addr);

            Bootstrap cb = GetLocalClientBootstrap();

            SetInterest(LoggingHandler.Event.WRITE, LoggingHandler.Event.FLUSH, LoggingHandler.Event.WRITABILITY);

            var clientChannel = await cb.ConnectAsync(addr);

            clientChannel.Configuration.WriteBufferLowWaterMark  = 512;
            clientChannel.Configuration.WriteBufferHighWaterMark = 1024;

            clientChannel.Pipeline.AddLast(new ChannelInboundHandlerAdapter0());

            Assert.True(clientChannel.IsWritable);

            await clientChannel.WriteAsync(CreateTestBuf(2000));

            await clientChannel.CloseAsync();

            AssertLog(
                // Case 1:
                "WRITABILITY: writable=False\n" +
                "FLUSH\n" +
                "WRITE\n" +
                "WRITABILITY: writable=False\n" +
                "WRITABILITY: writable=False\n" +
                "FLUSH\n" +
                "WRITABILITY: writable=True\n",
                // Case 2:
                "WRITABILITY: writable=False\n" +
                "FLUSH\n" +
                "WRITE\n" +
                "WRITABILITY: writable=False\n" +
                "FLUSH\n" +
                "WRITABILITY: writable=True\n" +
                "WRITABILITY: writable=True\n");
        }
Esempio n. 10
0
        public async Task RunEngineAsync(int port, IBasicHandler basicHandler, ICustomizeHandler handler)
        {
            bossGroup   = new MultithreadEventLoopGroup(1);
            workerGroup = new MultithreadEventLoopGroup();
            MessageDispatcher                 dispatcher   = new MessageDispatcher(this.BasicController, basicHandler, handler);
            List <ChannelServerHandler>       handlers     = new List <ChannelServerHandler>();
            RingObject <ChannelServerHandler> ringHandlers = null;

            if (!useDefaultThread)//此处相比默认handler增加了工作线程,默认工作线程为cpu核心*2
            {
                for (int i = 0; i < workThreadCount; i++)
                {
                    WorkerEngine <RequestInfo> workerEngine = new WorkerEngine <RequestInfo>(3000, 1, dispatcher.Process);
                    workerEngine.Start();
                    handlers.Add(new ChannelServerHandler(this.userManager, workerEngine));
                }
                ringHandlers = new RingObject <ChannelServerHandler>(handlers);
            }
            else
            {
                var cChannelHandlers = new List <ChannelServerHandler>()
                {
                    new ChannelServerHandler(this.userManager, dispatcher)
                };
                ringHandlers = new RingObject <ChannelServerHandler>(cChannelHandlers);
            }
            var bootstrap = new ServerBootstrap();

            bootstrap
            .Group(bossGroup, workerGroup)
            .Channel <TcpServerSocketChannel>()
            //.Option(ChannelOption.SoBacklog, 100)
            //.Handler(new LoggingHandler(LogLevel.INFO))
            .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast(OFrameDecoder.NewOFrameDecoder());
                pipeline.AddLast(ringHandlers.GetNext());
            }));

            IChannel bootstrapChannel = await bootstrap.BindAsync(port);
        }
Esempio n. 11
0
        public async Task TestCloseAsync()
        {
            var       group = new MultithreadEventLoopGroup();
            var       addr  = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId());
            Bootstrap cb    = new Bootstrap().RemoteAddress(addr).Group(group).Channel <LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                                 .Group(group)
                                 .Channel <LocalServerChannel>()
                                 .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);

            var handler = new CountingChannelPoolHandler();
            var pool    = new SimpleChannelPool(cb, handler);
            var ch1     = await pool.AcquireAsync();

            var ch2 = await pool.AcquireAsync();

            pool.ReleaseAsync(ch1).Wait(TimeSpan.FromSeconds(1));
            pool.ReleaseAsync(ch2).Wait(TimeSpan.FromSeconds(1));

            // Assert that returned channels are open before close
            Assert.True(ch1.Open);
            Assert.True(ch2.Open);

            // Close asynchronously with timeout
            await pool.CloseAsync().WithTimeout(TimeSpan.FromSeconds(1));

            // Assert channels were indeed closed
            Assert.False(ch1.Open);
            Assert.False(ch2.Open);

            await sc.CloseAsync();

            pool.Close();
            await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5));
        }
Esempio n. 12
0
        public void SetUp(BenchmarkContext context)
        {
            this.serverGroup = new MultithreadEventLoopGroup(_ => new EventLoop(), 1);

            Encoding    iso = Encoding.GetEncoding("ISO-8859-1");
            IByteBuffer buf = Unpooled.Buffer().WriteInt(3).WriteBytes(iso.GetBytes("ABC"));

            this.message = new byte[buf.ReadableBytes];
            buf.GetBytes(buf.ReaderIndex, this.message);

            this.inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName);
            var counterHandler = new CounterHandlerInbound(this.inboundThroughputCounter);

            this.signal = new ManualResetEventSlimReadFinishedSignal(this.resetEvent);

            // using default settings
            this.serverBufferAllocator = new PooledByteBufferAllocator();

            ServerBootstrap sb = new ServerBootstrap()
                                 .Group(this.serverGroup)
                                 .Channel <TcpServerChannel>()
                                 .ChildOption(ChannelOption.Allocator, this.serverBufferAllocator)
                                 .ChildHandler(new ActionChannelInitializer <TcpChannel>(channel =>
            {
                channel.Pipeline
                .AddLast(GetEncoder())
                .AddLast(GetDecoder())
                .AddLast(counterHandler)
                .AddLast(new ReadFinishedHandler(this.signal, WriteCount));
            }));

            // start server
            this.serverChannel = sb.BindAsync(TestAddress).Result;

            // connect to server
            var address = (IPEndPoint)this.serverChannel.LocalAddress;

            this.clientSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
            this.clientSocket.Connect(address.Address, address.Port);

            this.stream = new NetworkStream(this.clientSocket, true);
        }
Esempio n. 13
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            bossGroup             = new DispatcherEventLoopGroup();
            workerGroup           = new WorkerEventLoopGroup(bossGroup, configuration.EventLoopCount);
            serverBufferAllocator = new PooledByteBufferAllocator();
            //serverBufferAllocator = new UnpooledByteBufferAllocator();
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.Group(bossGroup, workerGroup);
            bootstrap.Channel <TcpServerChannel>();
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                bootstrap
                .Option(ChannelOption.SoReuseport, true)
                .ChildOption(ChannelOption.SoReuseaddr, true);
            }
            bootstrap
            .Option(ChannelOption.SoBacklog, configuration.SoBacklog)
            .ChildOption(ChannelOption.Allocator, serverBufferAllocator)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                using (var scope = serviceProvider.CreateScope())
                {
                    channel.Pipeline.AddLast("jt808TcpBuffer", new DelimiterBasedFrameDecoder(int.MaxValue,
                                                                                              Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }),
                                                                                              Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag })));
                    channel.Pipeline.AddLast("jt808TcpDecode", scope.ServiceProvider.GetRequiredService <JT808TcpDecoder>());
                    channel.Pipeline.AddLast("jt808TcpEncode", scope.ServiceProvider.GetRequiredService <JT808TcpEncoder>());
                    channel.Pipeline.AddLast("systemIdleState", new IdleStateHandler(
                                                 configuration.ReaderIdleTimeSeconds,
                                                 configuration.WriterIdleTimeSeconds,
                                                 configuration.AllIdleTimeSeconds));
                    channel.Pipeline.AddLast("jt808TcpConnection", scope.ServiceProvider.GetRequiredService <JT808TcpConnectionHandler>());
                    channel.Pipeline.AddLast("jt808TcpService", scope.ServiceProvider.GetRequiredService <JT808TcpServerHandler>());
                }
            }));
            logger.LogInformation($"JT808 TCP Server start at {IPAddress.Any}:{configuration.TcpPort}.");
            return(bootstrap.BindAsync(configuration.TcpPort)
                   .ContinueWith(i => bootstrapChannel = i.Result));
        }
Esempio n. 14
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (configuration.TcpPort <= 0)
            {
                return;
            }

            var bootstrap = new ServerBootstrap();

            serverBufferAllocator = new PooledByteBufferAllocator();
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                var dispatcher = new DispatcherEventLoopGroup();
                bossGroup   = dispatcher;
                workerGroup = new WorkerEventLoopGroup(dispatcher);
                bootstrap.Channel <TcpServerChannel>();
                bootstrap
                .Option(ChannelOption.SoReuseport, true)
                .ChildOption(ChannelOption.SoReuseaddr, true);
            }
            else
            {
                bossGroup   = new MultithreadEventLoopGroup(1);
                workerGroup = new MultithreadEventLoopGroup();
                bootstrap.Channel <TcpServerSocketChannel>();
            }
            bootstrap.Group(bossGroup, workerGroup);
            bootstrap
            .Option(ChannelOption.SoBacklog, configuration.SoBacklog)
            .ChildOption(ChannelOption.Allocator, serverBufferAllocator)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                var pipeline    = channel.Pipeline;
                using var scope = serviceProvider.CreateScope();
                pipeline.AddLast(new IdleStateHandler(configuration.ReaderIdleTimeSeconds, configuration.WriterIdleTimeSeconds, configuration.AllIdleTimeSeconds));
                pipeline.AddLast(scope.ServiceProvider.GetRequiredService <TcpMetadataDecoder>());
                pipeline.AddLast(scope.ServiceProvider.GetRequiredService <TcpMetadataEncoder>());
                pipeline.AddLast(scope.ServiceProvider.GetRequiredService <BranchTcpServerHandler>());
            }));
            logger.LogInformation($"TCP Server start at {IPAddress.Any}:{configuration.TcpPort}.");
            bootstrapChannel = await bootstrap.BindAsync(configuration.TcpPort);
        }
Esempio n. 15
0
        static async Task RunServer()
        {
            var eventListener = new ObservableEventListener();

            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);

            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler(LogLevel.INFO))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (EchoServerSettings.IsSsl)
                    {
                        pipeline.AddLast(TlsHandler.Server(new X509Certificate2("dotnetty.com.pfx", "password")));
                    }

                    pipeline.AddLast(new EchoServerHandler());
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(EchoServerSettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
                eventListener.Dispose();
            }
        }
Esempio n. 16
0
        private async Task TestSoLingerZeroCausesOnlyRstOnClose0(ServerBootstrap sb, Bootstrap cb)
        {
            AtomicReference <IChannel>  serverChannelRef = new AtomicReference <IChannel>();
            AtomicReference <Exception> throwableRef     = new AtomicReference <Exception>();
            CountdownEvent latch  = new CountdownEvent(1);
            CountdownEvent latch2 = new CountdownEvent(1);

            // SO_LINGER=0 means that we must send ONLY a RST when closing (not a FIN + RST).
            sb.ChildOption(ChannelOption.SoLinger, 0);
            sb.ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                serverChannelRef.CompareAndSet(null, ch);
                latch.SafeSignal();
            }));
            cb.Handler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(new ChannelInboundHandlerAdapter0(throwableRef, latch2));
            }));
            IChannel sc = await sb.BindAsync();

            IChannel cc = await cb.ConnectAsync(sc.LocalAddress);

            // Wait for the server to get setup.
            latch.Wait();

            // The server has SO_LINGER=0 and so it must send a RST when close is called.
            serverChannelRef.Value.CloseAsync().Ignore();

            // Wait for the client to get channelInactive.
            latch2.Wait();

            // Verify the client received a RST.
            var cause = throwableRef.Value;

            if (cause is object)
            {
                Assert.True(cause is SocketException, "actual [type, message]: [" + cause.GetType() + ", " + cause.Message + "]");

                //AssertRstOnCloseException((SocketException)cause, cc);
                Assert.True(cause.Message.Contains("reset") || cause.Message.Contains("closed"), "actual message: " + cause.Message);
            }
        }
Esempio n. 17
0
        public async Task TestBoundedChannelPoolSegment()
        {
            var       group = new MultithreadEventLoopGroup();
            var       addr  = new LocalAddress(LOCAL_ADDR_ID);
            Bootstrap cb    = new Bootstrap().RemoteAddress(addr).Group(group).Channel <LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                                 .Group(group)
                                 .Channel <LocalServerChannel>()
                                 .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);

            var handler = new CountingChannelPoolHandler();

            var pool = new SingleChannelPool(cb, handler);

            IChannel channel = await pool.AcquireAsync();

            IChannel channel2 = await pool.AcquireAsync();

            await pool.ReleaseAsync(channel);

            await Assert.ThrowsAsync <InvalidOperationException>(async() => await pool.ReleaseAsync(channel2));

            await channel2.CloseAsync();

            Assert.Equal(2, handler.ChannelCount);
            Assert.Equal(0, handler.AcquiredCount);
            Assert.Equal(1, handler.ReleasedCount);
            await sc.CloseAsync();

            await channel.CloseAsync();

            await channel2.CloseAsync();

            await group.ShutdownGracefullyAsync();
        }
Esempio n. 18
0
        public async Task TestUnhealthyChannelIsNotOffered()
        {
            var       group = new MultithreadEventLoopGroup();
            var       addr  = new LocalAddress(LOCAL_ADDR_ID);
            Bootstrap cb    = new Bootstrap().RemoteAddress(addr).Group(group).Channel <LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                                 .Group(group)
                                 .Channel <LocalServerChannel>()
                                 .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);

            var      handler  = new CountingChannelPoolHandler();
            var      pool     = new SimpleChannelPool(cb, handler);
            IChannel channel1 = await pool.AcquireAsync();

            await pool.ReleaseAsync(channel1);

            IChannel channel2 = await pool.AcquireAsync();

            //first check that when returned healthy then it actually offered back to the pool.
            Assert.Same(channel1, channel2);

            await channel1.CloseAsync();

            await pool.ReleaseAsync(channel1);

            IChannel channel3 = await pool.AcquireAsync();

            //channel1 was not healthy anymore so it should not get acquired anymore.
            Assert.NotSame(channel1, channel3);
            await sc.CloseAsync();

            await channel3.CloseAsync();

            await group.ShutdownGracefullyAsync();
        }
Esempio n. 19
0
        static async Task RunServerAsync()
        {
            ExampleHelper.SetConsoleLogger();

            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();
            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
            }
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler("LSTN"))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                    }
                    pipeline.AddLast(new LoggingHandler("CONN"));
                    pipeline.AddLast(new DiscardServerHandler());
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(ServerSettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Esempio n. 20
0
        public async Task <IChannel> startHttpPortAsync(string lport)
        {
            //X509Certificate2 tlsCertificate = null;
            //if (ServerSettings.IsSsl)
            //{
            //    tlsCertificate = new X509Certificate2(Path.Combine(commSetting.ProcessDirectory, "dotnetty.com.pfx"), "password");
            //}
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            }
            try
            {
                httpbootstrap.Group(httpbossGroup, httpworkerGroup);
                httpbootstrap.Channel <CustHttpServerSocketChannel>();

                httpbootstrap
                .Option(ChannelOption.SoBacklog, 8192)

                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    //  pipeline.AddLast("encoder", new HttpResponseEncoder());
                    pipeline.AddLast("decoder", new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize, true));
                    pipeline.AddLast("decoder2", new HttpObjectAggregator(maxContentLength));
                    pipeline.AddLast("handler", new HttpProxyServerHandler());
                }))
                .ChildOption(ChannelOption.SoKeepalive, true);

                httpbootstrapChannel = await httpbootstrap.BindAsync(IPAddress.IPv6Any, int.Parse(lport));

                Console.WriteLine($"Httpd started. Listening on {httpbootstrapChannel.LocalAddress}");

                return(httpbootstrapChannel);
            }
            catch (Exception ex)
            {
                Task.WaitAll(httpbossGroup.ShutdownGracefullyAsync(), httpworkerGroup.ShutdownGracefullyAsync());
                throw new Exception("服务启动失败");
            }
        }
        public async Task TestSocketReuse()
        {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            LocalHandler    serverHandler   = new LocalHandler("SERVER");

            serverBootstrap
            .Group(new DefaultEventLoopGroup(1), new DefaultEventLoopGroup())
            .Channel <LocalServerChannel>()
            .ChildHandler(serverHandler);
            Bootstrap    clientBootstrap = new Bootstrap();
            LocalHandler clientHandler   = new LocalHandler("CLIENT");

            clientBootstrap
            .Group(new DefaultEventLoopGroup())
            .Channel <LocalChannel>()
            .RemoteAddress(new LocalAddress(LOCAL_CHANNEL)).Handler(clientHandler);

            await serverBootstrap.BindAsync(new LocalAddress(LOCAL_CHANNEL));

            int count = 100;

            for (int i = 1; i < count + 1; i++)
            {
                var ch = await clientBootstrap.ConnectAsync();

                // SPIN until we get what we are looking for.
                int target = i * c_messageCountPerRun;
                while (serverHandler.Count.Value != target || clientHandler.Count.Value != target)
                {
                    Thread.Sleep(50);
                }
                Close(ch, clientHandler);
            }

            Assert.Equal(count * 2 * c_messageCountPerRun, serverHandler.Count.Value + clientHandler.Count.Value);

            Task.WaitAll(
                serverBootstrap.Group().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)),
                serverBootstrap.ChildGroup().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)),
                clientBootstrap.Group().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5))
                );
        }
        public void SetUp(BenchmarkContext context)
        {
            ServerGroup = new MultithreadEventLoopGroup(1);
            WorkerGroup = new MultithreadEventLoopGroup();


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

            message = Unpooled.Buffer().WriteInt(3).WriteBytes(iso.GetBytes("ABC")).ToArray();


            _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));
            }));

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

            // connect to server
            var address = (IPEndPoint)_serverChannel.LocalAddress;

            ClientSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetworkV6, SocketType.Stream,
                                                         ProtocolType.Tcp);
            ClientSocket.Connect(address.Address, address.Port);

            Stream = new NetworkStream(ClientSocket, true);
        }
Esempio n. 23
0
        public async Task StartAsync(EndPoint endPoint)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug($"准备启动服务主机,监听地址:{endPoint}。");
            }

            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();//Default eventLoopCount is Environment.ProcessorCount * 2
            var             bootstrap   = new ServerBootstrap();

            bootstrap
            .Channel <TcpServerSocketChannel>()
            .Option(ChannelOption.SoBacklog, 128)
            .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
            .Group(bossGroup, workerGroup)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                var pipeline = channel.Pipeline;
                pipeline.AddLast(new LengthFieldPrepender(4));
                pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));
                pipeline.AddLast(new TransportMessageChannelHandlerAdapter(_transportMessageDecoder));
                pipeline.AddLast(new ServerHandler(async(contenxt, message) =>
                {
                    var sender = new DotNettyServerMessageSender(_transportMessageEncoder, contenxt);
                    await OnReceived(sender, message);
                }, _logger));
            }));
            try
            {
                _channel = await bootstrap.BindAsync(endPoint);

                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug($"服务主机启动成功,监听地址:{endPoint}。");
                }
            }
            catch
            {
                _logger.LogError($"服务主机启动失败,监听地址:{endPoint}。 ");
            }
        }
Esempio n. 24
0
        static async Task Server()
        {
            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.Group(bossGroup, workerGroup)
            .Channel <TcpServerSocketChannel>()
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                channel.Pipeline.AddLast("echo", new ServerHandler());
            }));

            IChannel boundChannel = await bootstrap.BindAsync(12345);

            Console.ReadLine();

            await boundChannel.CloseAsync();
        }
Esempio n. 25
0
        public async Task Run()
        {
            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup(5);
            var bootstrap   = new ServerBootstrap();

            bootstrap
            .Group(bossGroup, workerGroup)
            .Channel <TcpServerSocketChannel>()
            .Option(ChannelOption.SoBacklog, 100)
            .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast(new DeCoder());
                pipeline.AddLast(new EnCoder());
                pipeline.AddLast(new EnCoder2());
                pipeline.AddLast(new EchoServerHandler());
            }));
            bootstrapChannel = await bootstrap.BindAsync(2012);
        }
        Task <IChannel> NewServer(bool autoRead, params IChannelHandler[] handlers)
        {
            Assert.True(handlers.Length >= 1);

            var serverBootstrap = new ServerBootstrap();

            serverBootstrap.Group(this.group)
            .Channel <TcpServerSocketChannel>()
            .ChildOption(ChannelOption.AutoRead, autoRead)
            .ChildHandler(
                new ActionChannelInitializer <IChannel>(
                    ch =>
            {
                IChannelPipeline pipeline = ch.Pipeline;
                pipeline.AddLast(new OneByteToThreeStringsDecoder());
                pipeline.AddLast(handlers);
            }));

            return(serverBootstrap.BindAsync(IPAddress.Loopback, 0));
        }
Esempio n. 27
0
        /// <summary>
        /// Starts the network.
        /// </summary>
        static async Task Bootstrap()
        {
            var boss      = new MultithreadEventLoopGroup(1);
            var worker    = new MultithreadEventLoopGroup();
            var bootstrap = new ServerBootstrap();

            bootstrap.Group(boss, worker);
            bootstrap.Option(ChannelOption.SoKeepalive, true);
            bootstrap.Channel <TcpServerSocketChannel>();
            bootstrap.ChildHandler(new ActionChannelInitializer <ISocketChannel>((ch) =>
            {
                IChannelPipeline pipeline = ch.Pipeline;

                pipeline.AddLast("decoder", new ConnectionDecoder());
                pipeline.AddLast("encoder", new ConnectionEncoder());
                pipeline.AddLast("handler", new NetworkHandler(ch));
            }));

            await bootstrap.BindAsync(IPAddress.Any, Constants.HOST_PORT);
        }
Esempio n. 28
0
        public Property TcpSocketServerChannel_can_bind_on_any_valid_EndPoint(EndPoint ep)
        {
            IChannel c = null;

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

                c = sb.BindAsync(ep).Result;

                return(c.IsOpen.Label("Channel should be open").And(c.IsActive).Label("Channel should be active"));
            }
            finally
            {
                c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
            }
        }
Esempio n. 29
0
        public async Task StartAsync()
        {
            try
            {
                this.logger.LogInformation("Starting MQTT head");

                ServerBootstrap bootstrap = this.SetupServerBootstrap();

                this.logger.LogInformation("Initializing TLS endpoint on port {0} for MQTT head.", MqttsPort);

                this.serverChannel = await bootstrap.BindAsync(!Socket.OSSupportsIPv6?IPAddress.Any : IPAddress.IPv6Any, MqttsPort);

                this.logger.LogInformation("Started MQTT head");
            }
            catch (Exception e)
            {
                this.logger.LogError("Failed to start MQTT server {0}", e);
                await this.CloseAsync(CancellationToken.None);
            }
        }
Esempio n. 30
0
        public static async Task RunServerAsync(int port, IPacketCryptoFactory factory)
        {
            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Option(ChannelOption.SoBacklog, 100)
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast("encoder", (MessageToMessageEncoder <string>)factory.GetEncoder());
                    pipeline.AddLast("decoder", (MessageToMessageDecoder <IByteBuffer>)factory.GetDecoder());
                    pipeline.AddLast("session", new ClientSession(channel));
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(port).ConfigureAwait(false);

                Log.Info($"[LISTENING] Server is listening");
                Log.Info($"-> PORT : {port}");

                while (Console.ReadLine() != "quit")
                {
                    Thread.Sleep(2000);
                }

                await bootstrapChannel.CloseAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Log.Error("[SERVER]", ex);
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Esempio n. 31
0
        private async Task TestReadPendingIsResetAfterEachRead0(ServerBootstrap sb, Bootstrap cb)
        {
            IChannel serverChannel = null;
            IChannel clientChannel = null;

            try
            {
                MyInitializer serverInitializer = new MyInitializer();
                sb.Option(ChannelOption.SoBacklog, 1024);
                sb.ChildHandler(serverInitializer);

                serverChannel = await sb.BindAsync();

                cb.Handler(new MyInitializer());
                clientChannel = await cb.ConnectAsync(serverChannel.LocalAddress);

                await clientChannel.WriteAndFlushAsync(Unpooled.WrappedBuffer(new byte[1024]));

                // We expect to get 2 exceptions (1 from BuggyChannelHandler and 1 from ExceptionHandler).
                Assert.True(serverInitializer._exceptionHandler._latch1.Wait(TimeSpan.FromSeconds(5)));

                // After we get the first exception, we should get no more, this is expected to timeout.
                Assert.False(serverInitializer._exceptionHandler._latch2.Wait(TimeSpan.FromSeconds(1)),
                             "Encountered " + serverInitializer._exceptionHandler._count.Value + " exceptions when 1 was expected");
            }
            finally
            {
                if (serverChannel != null)
                {
                    await serverChannel.CloseAsync();
                }
                if (clientChannel != null)
                {
                    await clientChannel.CloseAsync();
                }
                Task.WaitAll(
                    sb.Group().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)),
                    sb.ChildGroup().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)),
                    cb.Group().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)));
            }
        }
        //static
        public async Task StartHttp()
        {
            ServerBootstrap bootstrap = null;

            try
            {
                // if (bootstrap == null)
                {
                    IEventLoopGroup group;
                    IEventLoopGroup workGroup;
                    bootstrap = new ServerBootstrap();
                    group     = new MultithreadEventLoopGroup(1);
                    workGroup = new MultithreadEventLoopGroup();

                    bootstrap.Group(group, workGroup);
                    bootstrap.Channel <TcpServerSocketChannel>();
                    bootstrap
                    .Option(ChannelOption.SoBacklog, 8192)
                    .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                    {
                        IChannelPipeline pipeline = channel.Pipeline;
                        //if (tlsCertificate != null)
                        //{
                        //    pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                        //}
                        pipeline.AddLast("encoder", new HttpResponseEncoder());
                        pipeline.AddLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
                        pipeline.AddLast("handler", this.adapter);
                    }));
                    IChannel bootstrapChannel = await bootstrap.BindAsync(System.Net.IPAddress.IPv6Any, this.port);
                }
                if (bootstrap == null)
                {
                }
            }
            catch (Exception ex)
            {
                //if (log != null)
                //    log.Log(new WarningLogEntry() { Exception = ex });
            }
        }
Esempio n. 33
0
        public static async System.Threading.Tasks.Task RunClientAsync(string[] args)
        {
            if (args == null || args.Length != 1 || !int.TryParse(args[0], out int port))
            {
                System.Console.WriteLine("Usage: port");
                return;
            }
            MultithreadEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            MultithreadEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            try
            {
                ServerBootstrap b = new ServerBootstrap();
                b.Group(bossGroup, workerGroup).Channel <TcpServerSocketChannel>().Handler(new LoggingHandler(LogLevel.INFO)).ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline p = channel.Pipeline;

                    p.AddLast(new ProtobufVarint32FrameDecoder());
                    p.AddLast(new ProtobufDecoder(ProtobufCommand.Command.Parser));
                    p.AddLast(new ProtobufVarint32LengthFieldPrepender());
                    p.AddLast(new ProtobufEncoder());
                    p.AddLast(new ServerHandler());
                }));
                IChannel ch = await b.BindAsync(port);

                Server server = new Server(new ServerHandler());
                server.Loop();
                await ch.CloseAsync();
            } catch (System.Exception e)
            {
                int line = (new StackTrace(e, true)).GetFrame(0).GetFileLineNumber();
                System.Console.WriteLine("Error :" + e.Message + "on line " + line);
            } finally
            {
                await bossGroup.ShutdownGracefullyAsync();

                await workerGroup.ShutdownGracefullyAsync();

                System.Console.WriteLine("Server closed gracefully");
            }
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            bossGroup             = new DispatcherEventLoopGroup();
            workerGroup           = new WorkerEventLoopGroup(bossGroup, configuration.EventLoopCount);
            serverBufferAllocator = new PooledByteBufferAllocator();
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.Group(bossGroup, workerGroup);
            bootstrap.Channel <TcpServerChannel>();
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                bootstrap
                .Option(ChannelOption.SoReuseport, true)
                .ChildOption(ChannelOption.SoReuseaddr, true);
            }
            bootstrap
            .Option(ChannelOption.SoBacklog, 8192)
            .ChildOption(ChannelOption.Allocator, serverBufferAllocator)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast(new HttpServerCodec());
                pipeline.AddLast(new CorsHandler(CorsConfigBuilder
                                                 .ForAnyOrigin()
                                                 .AllowNullOrigin()
                                                 .AllowedRequestMethods(HttpMethod.Get, HttpMethod.Post, HttpMethod.Options, HttpMethod.Delete)
                                                 .AllowedRequestHeaders((AsciiString)"origin", (AsciiString)"range", (AsciiString)"accept-encoding", (AsciiString)"referer", (AsciiString)"Cache-Control", (AsciiString)"X-Proxy-Authorization", (AsciiString)"X-Requested-With", (AsciiString)"Content-Type")
                                                 .ExposeHeaders((StringCharSequence)"Server", (StringCharSequence)"range", (StringCharSequence)"Content-Length", (StringCharSequence)"Content-Range")
                                                 .AllowCredentials()
                                                 .Build()));
                pipeline.AddLast(new HttpObjectAggregator(int.MaxValue));
                using (var scope = serviceProvider.CreateScope())
                {
                    pipeline.AddLast("JT1078HttpServerHandler", scope.ServiceProvider.GetRequiredService <JT1078HttpServerHandler>());
                }
            }));
            logger.LogInformation($"JT1078 Http Server start at {IPAddress.Any}:{configuration.HttpPort}.");
            return(bootstrap.BindAsync(configuration.HttpPort)
                   .ContinueWith(i => bootstrapChannel = i.Result));
        }
        public void FlushNotDiscarded()
        {
            var executorService = new SingleThreadEventExecutor("Discarded", TimeSpan.FromMilliseconds(100));

            try
            {
                _sb = new ServerBootstrap();
                _sb.Group(new MultithreadEventLoopGroup(1), new MultithreadEventLoopGroup());
                _sb.Channel <TcpServerSocketChannel>();
                _sb.ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddLast(new Http2FrameCodecBuilder(true).Build());
                    ch.Pipeline.AddLast(new Http2MultiplexHandler(new TestChannelInboundHandlerAdapter(executorService)));
                }));
                var loopback = IPAddress.IPv6Loopback;
                _serverChannel = _sb.BindAsync(loopback, 0).GetAwaiter().GetResult();

                CountdownEvent latch = new CountdownEvent(1);

                _bs = new Bootstrap();
                _bs.Group(new MultithreadEventLoopGroup());
                _bs.Channel <TcpSocketChannel>();
                _bs.Handler(new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddLast(new Http2FrameCodecBuilder(false).Build());
                    ch.Pipeline.AddLast(new Http2MultiplexHandler(DISCARD_HANDLER.Instance));
                }));
                var port = ((IPEndPoint)_serverChannel.LocalAddress).Port;
                var ccf  = _bs.ConnectAsync(loopback, port);
                _clientChannel = ccf.GetAwaiter().GetResult();
                Http2StreamChannelBootstrap h2Bootstrap = new Http2StreamChannelBootstrap(_clientChannel);
                h2Bootstrap.Handler(new TestFlushNotDiscardedHandler(latch));
                IHttp2StreamChannel streamChannel = h2Bootstrap.OpenAsync().GetAwaiter().GetResult();
                streamChannel.WriteAndFlushAsync(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), true)).GetAwaiter().GetResult();
                latch.Wait();
            }
            finally
            {
                executorService.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5));
            }
        }
Esempio n. 36
0
        public async Task RunAsync(int threadCount, CancellationToken cancellationToken, RecieveServiceRequestDelegate recieveServiceRequest)
        {
            Contract.Requires(threadCount > 0);
            try
            {
                LogsManager.Info("通用服务开始启动!");
                this.parentEventLoopGroup = new MultithreadEventLoopGroup(1);
                this.eventLoopGroup       = new MultithreadEventLoopGroup(threadCount);
                ServerBootstrap bootstrap = this.SetupBootstrap(recieveServiceRequest);

                this.serverChannel = await bootstrap.BindAsync(port);

                cancellationToken.Register(this.CloseAsync);
                LogsManager.Info("通用服务成功启动!");
            }
            catch (Exception ex)
            {
                LogsManager.Error("通用服务启动失败");
                this.CloseAsync();
            }
        }
Esempio n. 37
0
        private static async Task RunServerAsync()
        {
            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            try {
                ServerBootstrap bootstrap = new ServerBootstrap()
                                            .Group(bossGroup, workerGroup)
                                            .Channel <TcpServerSocketChannel>()
                                            .ChildHandler(new ActionChannelInitializer <IChannel>(channel => {
                    channel.Pipeline.AddLast(new TimeEncoder(), new TimeServerHandler());
                }));

                IChannel boundChannel = await bootstrap.BindAsync(Port);

                await boundChannel.CloseCompletion;
            } finally {
                await Task.WhenAll(bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                                   workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            }
        }
Esempio n. 38
0
        /// <summary>
        /// 启动主机。
        /// </summary>
        /// <param name="endPoint">主机终结点。</param>
        /// <returns>一个任务。</returns>
        public async Task StartAsync(EndPoint endPoint)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
                _logger.Debug($"准备启动服务主机,监听地址:{endPoint}。");

            var bossGroup = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();
            var bootstrap = new ServerBootstrap();
            bootstrap
                .Group(bossGroup, workerGroup)
                .Channel<TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
                {
                    var pipeline = channel.Pipeline;
                    pipeline.AddLast(new LengthFieldPrepender(4));
                    pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));
                    pipeline.AddLast(new ServerHandler(_serializer, _serviceEntryLocate, _logger));
                }));
            _channel = await bootstrap.BindAsync(endPoint);

            if (_logger.IsEnabled(LogLevel.Debug))
                _logger.Debug($"服务主机启动成功,监听地址:{endPoint}。");
        }
Esempio n. 39
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);
            }
        }
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();
            }
        }
        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
                {
                }
            }
        }
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 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. 47
0
        /// <summary>
        /// Starts Echo server.
        /// </summary>
        /// <returns>function to trigger closure of the server.</returns>
        async Task<Func<Task>> StartServerAsync(bool tcpNoDelay, Action<IChannel> childHandlerSetupAction, TaskCompletionSource testPromise)
        {
            var bossGroup = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();
            bool started = false;
            //var tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password");
            try
            {
                ServerBootstrap b = new ServerBootstrap()
                    .Group(bossGroup, workerGroup)
                    .Channel<TcpServerSocketChannel>()
                    .Handler(new ExceptionCatchHandler(ex => testPromise.TrySetException(ex)))
                    .ChildHandler(new ActionChannelInitializer<ISocketChannel>(childHandlerSetupAction))
                    .ChildOption(ChannelOption.TcpNodelay, tcpNoDelay);

                this.output.WriteLine("Configured ServerBootstrap: {0}", b);

                IChannel serverChannel = await b.BindAsync(Port);

                this.output.WriteLine("Bound server channel: {0}", serverChannel);

                started = true;

                return async () =>
                {
                    try
                    {
                        await serverChannel.CloseAsync();
                    }
                    finally
                    {
                        Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
                    }
                };
            }
            finally
            {
                if (!started)
                {
                    Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
                }
            }
        }
        public Property TcpSocketServerChannel_can_bind_on_any_valid_EndPoint(EndPoint ep)
        {
            IChannel c = null;
            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;
            }

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

                c = sb.BindAsync(ep).Result;

                return c.IsOpen.Label("Channel should be open").And(c.IsActive).Label("Channel should be active");
            }
            finally
            {
                c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200));
            }
        }
        public void SetUp(BenchmarkContext context)
        {
            ServerGroup = new MultithreadEventLoopGroup(1);
            WorkerGroup = new MultithreadEventLoopGroup();


            var iso = Encoding.GetEncoding("ISO-8859-1");
            message = Unpooled.Buffer().WriteInt(3).WriteBytes(iso.GetBytes("ABC")).ToArray();


            _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));
                        }));

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

            // connect to server
            var address = (IPEndPoint) _serverChannel.LocalAddress;
            ClientSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetworkV6, SocketType.Stream,
                ProtocolType.Tcp);
            ClientSocket.Connect(address.Address, address.Port);

            Stream = new NetworkStream(ClientSocket, true);
        }
        public void SetUp(BenchmarkContext context)
        {
            TaskScheduler.UnobservedTaskException += (sender, args) => Console.WriteLine(args.Exception);

            this.ClientGroup = new MultithreadEventLoopGroup(1);
            this.ServerGroup = new MultithreadEventLoopGroup(1);
            this.WorkerGroup = new MultithreadEventLoopGroup();

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

            this.inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName);
            this.outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName);
            var counterHandler = new CounterHandlerInbound(this.inboundThroughputCounter);
            this.signal = new ManualResetEventSlimReadFinishedSignal(this.ResetEvent);

            // reserve up to 10mb of 16kb buffers on both client and server; we're only sending about 700k worth of messages
            this.serverBufferAllocator = new PooledByteBufferAllocator();
            this.clientBufferAllocator = new PooledByteBufferAllocator();

            Assembly assembly = typeof(TcpChannelPerfSpecs).Assembly;
            byte[] certificateData;
            using (Stream sourceStream = assembly.GetManifestResourceStream(assembly.GetManifestResourceNames()[0]))
            using (var tempStream = new MemoryStream())
            {
                sourceStream.CopyTo(tempStream);
                certificateData = tempStream.ToArray();
            }
            var tlsCertificate = new X509Certificate2(certificateData, "password");
            string targetHost = tlsCertificate.GetNameInfo(X509NameType.DnsName, false);

            ServerBootstrap sb = new ServerBootstrap()
                .Group(this.ServerGroup, this.WorkerGroup)
                .Channel<TcpServerSocketChannel>()
                .ChildOption(ChannelOption.Allocator, this.serverBufferAllocator)
                .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel =>
                {
                    channel.Pipeline
                        //.AddLast(TlsHandler.Server(tlsCertificate))
                        .AddLast(this.GetEncoder())
                        .AddLast(this.GetDecoder())
                        .AddLast(counterHandler)
                        .AddLast(new CounterHandlerOutbound(this.outboundThroughputCounter))
                        .AddLast(new ReadFinishedHandler(this.signal, WriteCount));
                }));

            Bootstrap cb = new Bootstrap()
                .Group(this.ClientGroup)
                .Channel<TcpSocketChannel>()
                .Option(ChannelOption.Allocator, this.clientBufferAllocator)
                .Handler(new ActionChannelInitializer<TcpSocketChannel>(
                    channel =>
                    {
                        channel.Pipeline
                            //.AddLast(TlsHandler.Client(targetHost, null, (sender, certificate, chain, errors) => true))
                            .AddLast(this.GetEncoder())
                            .AddLast(this.GetDecoder())
                            .AddLast(counterHandler)
                            .AddLast(new CounterHandlerOutbound(this.outboundThroughputCounter));
                    }));

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

            // connect to server
            this.clientChannel = cb.ConnectAsync(this.serverChannel.LocalAddress).Result;
        }
Esempio n. 51
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. 52
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;
        }
        async Task EnsureServerInitializedAsync()
        {
            if (this.ServerAddress != null)
            {
                return;
            }

            int threadCount = Environment.ProcessorCount;
            var executorGroup = new MultithreadEventLoopGroup(threadCount);
            var bufAllocator = new PooledByteBufferAllocator(16 * 1024, 10 * 1024 * 1024 / threadCount); // reserve 10 MB for 64 KB buffers
            BlobSessionStatePersistenceProvider sessionStateProvider = await BlobSessionStatePersistenceProvider.CreateAsync(
                this.settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageConnectionString"),
                this.settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageContainerName"));
            TableQos2StatePersistenceProvider qos2StateProvider = await TableQos2StatePersistenceProvider.CreateAsync(
                this.settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageConnectionString"),
                this.settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageTableName"));
            var settings = new Settings(this.settingsProvider);
            var authProvider = new SasTokenAuthenticationProvider();
            var topicNameRouter = new TopicNameRouter();

            DeviceClientFactoryFunc deviceClientFactoryFactory = IotHubDeviceClient.PreparePoolFactory(settings.IotHubConnectionString + ";DeviceId=stub", "a", 1);

            ServerBootstrap server = new ServerBootstrap()
                .Group(executorGroup)
                .Channel<TcpServerSocketChannel>()
                .ChildOption(ChannelOption.Allocator, bufAllocator)
                .ChildOption(ChannelOption.AutoRead, false)
                .ChildHandler(new ActionChannelInitializer<IChannel>(ch =>
                {
                    ch.Pipeline.AddLast(TlsHandler.Server(this.tlsCertificate));
                    ch.Pipeline.AddLast(
                        MqttEncoder.Instance,
                        new MqttDecoder(true, 256 * 1024),
                        new MqttIotHubAdapter(
                            settings,
                            deviceClientFactoryFactory,
                            sessionStateProvider,
                            authProvider,
                            topicNameRouter,
                            qos2StateProvider),
                        new XUnitLoggingHandler(this.output));
                }));

            IChannel serverChannel = await server.BindAsync(IPAddress.Any, this.ProtocolGatewayPort);

            this.ScheduleCleanup(async () =>
            {
                await serverChannel.CloseAsync();
                await executorGroup.ShutdownGracefullyAsync();
            });
            this.ServerAddress = IPAddress.Loopback;
        }
        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
                {
                }
            }
        }
        public void SetUp(BenchmarkContext context)
        {
            this.ServerGroup = new MultithreadEventLoopGroup(1);
            this.WorkerGroup = new MultithreadEventLoopGroup();

            Encoding iso = Encoding.GetEncoding("ISO-8859-1");
            this.message = Unpooled.Buffer().WriteInt(3).WriteBytes(iso.GetBytes("ABC")).ToArray();

            this.inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName);
            var counterHandler = new CounterHandlerInbound(this.inboundThroughputCounter);
            this.signal = new ManualResetEventSlimReadFinishedSignal(this.ResetEvent);

            // using default settings
            this.serverBufferAllocator = new PooledByteBufferAllocator();

            ServerBootstrap sb = new ServerBootstrap()
                .Group(this.ServerGroup, this.WorkerGroup)
                .Channel<TcpServerSocketChannel>()
                .ChildOption(ChannelOption.Allocator, this.serverBufferAllocator)
                .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel =>
                {
                    channel.Pipeline
                        .AddLast(this.GetEncoder())
                        .AddLast(this.GetDecoder())
                        .AddLast(counterHandler)
                        .AddLast(new ReadFinishedHandler(this.signal, WriteCount));
                }));

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

            // connect to server
            var address = (IPEndPoint)this.serverChannel.LocalAddress;
            this.ClientSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
            this.ClientSocket.Connect(address.Address, address.Port);

            this.Stream = new NetworkStream(this.ClientSocket, true);
        }
Esempio n. 56
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);
            }
        }
        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);
        }
Esempio n. 58
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());
            }
        }