Beispiel #1
0
        private static async Task TestParentHandler0(bool channelInitializer)
        {
            LocalAddress   addr      = new LocalAddress(Guid.NewGuid().ToString());
            CountdownEvent readLatch = new CountdownEvent(1);
            CountdownEvent initLatch = new CountdownEvent(1);

            IChannelHandler handler = new TestHandler(readLatch, initLatch);

            IEventLoopGroup group = new DefaultEventLoopGroup(1);
            IChannel        sch   = null;
            IChannel        cch   = null;

            try
            {
                ServerBootstrap sb = new ServerBootstrap();
                sb.Channel <LocalServerChannel>()
                .Group(group)
                .ChildHandler(new ChannelHandlerAdapter());
                if (channelInitializer)
                {
                    sb.Handler(new ActionChannelInitializer <IChannel>(ch => ch.Pipeline.AddLast(handler)));
                }
                else
                {
                    sb.Handler(handler);
                }

                Bootstrap cb = new Bootstrap();
                cb.Group(group)
                .Channel <LocalChannel>()
                .Handler(new ChannelHandlerAdapter());

                sch = await sb.BindAsync(addr);

                cch = await cb.ConnectAsync(addr);

                initLatch.Wait();
                readLatch.Wait();
            }
            finally
            {
                if (sch != null)
                {
                    await sch.CloseAsync();
                }
                if (cch != null)
                {
                    await cch.CloseAsync();
                }
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5));
            }
        }
Beispiel #2
0
        public async Task StartAsync(ServerBootstrap bootstrap)
        {
            bootstrap.Channel <TcpServerSocketChannel>();
            bootstrap
            .Handler(new LoggingHandler($"{this._def.Name}", DotNetty.Handlers.Logging.LogLevel.INFO))
            .ChildHandler(new ActionChannelInitializer <IChannel>(c =>
            {
                this._pipelineSetup(c.Pipeline);
            }));
            IPAddress address = null;

            address = GetIPAddress();

            // bootstrap.Option(nettyServerConfig.BootstrapOptions);
            _serverChannel = await bootstrap.BindAsync(address, this._requestedPort);

            var actualSocket = _serverChannel.LocalAddress;

            IPEndPoint localPoint = _serverChannel.LocalAddress as IPEndPoint;

            _actualPort = localPoint?.Port ?? 0;
            if (_actualPort == 0)
            {
                DnsEndPoint dnsPoint = _serverChannel.LocalAddress as DnsEndPoint;
                _actualPort = dnsPoint?.Port ?? 0;
            }
            //Preconditions.checkState(actualPort != 0 && (actualPort == requestedPort || requestedPort == 0));
            _logger.LogInformation($"transport {_def.Name}:{_actualPort} was started.");
        }
Beispiel #3
0
        public async void Start(int port)
        {
            IEventLoopGroup boss_group   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup worker_group = new MultithreadEventLoopGroup(Args.Instance.Node.TcpNettyWorkThreadNum);

            try
            {
                ServerBootstrap bootstrap = new ServerBootstrap();

                bootstrap.Group(boss_group, worker_group);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap.Option(ChannelOption.SoKeepalive, true);
                bootstrap.Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default);
                bootstrap.Option(ChannelOption.ConnectTimeout, TimeSpan.FromSeconds(Args.Instance.Node.ConnectionTimeout));
                bootstrap.Handler(new LoggingHandler());
                bootstrap.ChildHandler(new NettyChannelInitializer("", false));

                Logger.Info("Tcp listener started, bind port : " + port);

                this.channel = await bootstrap.BindAsync(port);
            }
            catch (System.Exception e)
            {
                Logger.Error(e.Message, e);
            }
            finally
            {
            }
        }
 protected void Init()
 {
     _bootstrap.Group(_bossEventLoopGroup, _workerEventLoopGroup);
     _bootstrap.Channel <TcpServerSocketChannel>();
     _bootstrap.Option(ChannelOption.SoLinger, 0);
     _bootstrap.Option(ChannelOption.SoBacklog, Backlog);
     _bootstrap.Handler(new LoggingHandler(LogLevel.INFO));
     _bootstrap.ChildHandler(new InboundSessionInitializer(inboundSession));
     _bootstrap.ChildOption(ChannelOption.SoLinger, 0);
     _bootstrap.ChildOption(ChannelOption.SoKeepalive, true);
     _bootstrap.ChildOption(ChannelOption.TcpNodelay, true);
     _bootstrap.ChildOption(ChannelOption.SoReuseaddr, true);
 }
Beispiel #5
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);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap.Option(ChannelOption.SoBacklog, 100);
                bootstrap.Handler(new LoggingHandler("SRV-LSTN"));
                bootstrap.ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate));
                    }
                    //pipeline.AddLast(new LoggingHandler("SRV-CONN"));
                    // pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    // pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast("echo", new EchoServerHandler());
                    pipeline.AddLast("User", new UserHandler());

                    // Action<string> messageTarget = ShowMessage;
                }));


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

                Console.ReadLine();

                await boundChannel.CloseAsync();
            }
            finally
            {
                await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            }
        }
Beispiel #6
0
        void SimpleEcho0(ServerBootstrap sb, Bootstrap cb, bool additionalExecutor, bool autoRead)
        {
            var sh = new EchoHandler(autoRead, this.data, this.output);
            var ch = new EchoHandler(autoRead, this.data, this.output);

            if (additionalExecutor)
            {
                sb.ChildHandler(new ActionChannelInitializer <TcpChannel>(channel =>
                {
                    channel.Pipeline.AddLast(this.group, sh);
                }));
                cb.Handler(new ActionChannelInitializer <TcpChannel>(channel =>
                {
                    channel.Pipeline.AddLast(this.group, ch);
                }));
            }
            else
            {
                sb.ChildHandler(sh);
                sb.Handler(new ErrorOutputHandler(this.output));
                cb.Handler(ch);
            }
            sb.ChildOption(ChannelOption.AutoRead, autoRead);
            cb.Option(ChannelOption.AutoRead, autoRead);

            // start server
            Task <IChannel> task = sb.BindAsync(LoopbackAnyPort);

            Assert.True(task.Wait(DefaultTimeout), "Server bind timed out");
            this.serverChannel = task.Result;
            Assert.NotNull(this.serverChannel.LocalAddress);
            var endPoint = (IPEndPoint)this.serverChannel.LocalAddress;

            // connect to server
            task = cb.ConnectAsync(endPoint);
            Assert.True(task.Wait(DefaultTimeout), "Connect to server timed out");
            this.clientChannel = task.Result;
            Assert.NotNull(this.clientChannel.LocalAddress);

            for (int i = 0; i < this.data.Length;)
            {
                int         length = Math.Min(this.random.Next(1024 * 64), this.data.Length - i);
                IByteBuffer buf    = Unpooled.WrappedBuffer(this.data, i, length);
                this.clientChannel.WriteAndFlushAsync(buf);
                i += length;
            }

            Assert.True(Task.WhenAll(ch.Completion, sh.Completion).Wait(DefaultTimeout), "Echo read/write timed out");
        }
        void CloseForcibly0(ServerBootstrap sb, Bootstrap cb)
        {
            sb.Handler(new InboundHandler())
            .ChildHandler(new ChannelHandlerAdapter());
            cb.Handler(new ChannelHandlerAdapter());

            // start server
            Task <IChannel> task = sb.BindAsync(LoopbackAnyPort);

            Assert.True(task.Wait(DefaultTimeout), "Server bind timed out");
            this.serverChannel = task.Result;
            Assert.NotNull(this.serverChannel.LocalAddress);
            var endPoint = (IPEndPoint)this.serverChannel.LocalAddress;

            // connect to server
            task = cb.ConnectAsync(endPoint);
            Assert.True(task.Wait(DefaultTimeout), "Connect to server timed out");
            this.clientChannel = task.Result;
            Assert.NotNull(this.clientChannel.LocalAddress);
            this.clientChannel.CloseAsync().Wait(DefaultTimeout);

            this.serverChannel.CloseAsync().Wait(DefaultTimeout);
        }
        protected void Init()
        {
            InternalLoggerFactory.DefaultFactory.AddProvider(
                new ConsoleLoggerProvider(
                    (text, level) => level >= Microsoft.Extensions.Logging.LogLevel.Warning, true)
                );

            _bootstrap.Group(_bossEventLoopGroup, _workerEventLoopGroup); // 设置主和工作线程组
            _bootstrap.Channel <TcpServerSocketChannel>();                // 设置通道模式为TcpSocket

            //当服务器请求处理线程全满时,用于临时存放已完成三次握手的请求的队列的最大长度
            _bootstrap.Option(ChannelOption.SoBacklog, Backlog);//ChannelOption.SO_BACKLOG, 1024
            _bootstrap.Handler(new LoggingHandler(LogLevel.WARN));

            //_bootstrap.ChildHandler(new InboundSessionInitializer(inboundSession));
            //_bootstrap.ChildOption(ChannelOption.SoLinger,0);//Socket关闭时的延迟时间(秒)

            //注册
            _bootstrap.ChildHandler(new DataServerInitializer());

            _bootstrap.ChildOption(ChannelOption.SoKeepalive, true);//是否启用心跳保活机制

            //_bootstrap.ChildOption(ChannelOption.TcpNodelay,true);//启用/禁用Nagle算法
        }
Beispiel #9
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                System.Runtime.GCSettings.LatencyMode = System.Runtime.GCLatencyMode.SustainedLowLatency;
            }


            //if (_options.UseLibuv)
            //{
            //    var dispatcher =  new DispatcherEventLoopGroup();
            //    _bossGroup = dispatcher;
            //    _workerGroup = new WorkerEventLoopGroup(dispatcher);
            //}
            //else
            {
                // 主的线程
                _bossGroup = new MultithreadEventLoopGroup(1);
                // 工作线程,默认根据CPU计算
                _workerGroup = new MultithreadEventLoopGroup();
            }

            var bootstrap = new ServerBootstrap()
                            .Group(_bossGroup, _workerGroup);

            //if (_options.UseLibuv)
            {
                //bootstrap.Channel<TcpServerChannel>();
            }
            //else
            {
                bootstrap.Channel <TcpServerSocketChannel>();
            }

            bootstrap.Option(ChannelOption.SoBacklog, _options.SoBacklog); //NOTE: 是否可以公开更多Netty的参数

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                bootstrap
                .Option(ChannelOption.SoReuseport, true)
                .ChildOption(ChannelOption.SoReuseaddr, true);
            }

            X509Certificate2 tlsCertificate = null;

            if (!string.IsNullOrEmpty(_options.Certificate))
            {
                tlsCertificate = new X509Certificate2(_options.Certificate, _options.CertificatePassword);
            }

            _ = bootstrap.Handler(new LoggingHandler("LSTN"))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                var pipeline = channel.Pipeline;


                if (tlsCertificate != null)
                {
                    pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate));
                }

                pipeline.AddLast(new LoggingHandler("CONN"));

                foreach (var kv in _handlerPipeline.BuildPipeline(true))
                {
                    pipeline.AddLast(kv.Key, kv.Value);
                }

                //业务处理Handler,即解码成功后如何处理消息的类
                pipeline.AddLast(new TcpServerChannelHandlerAdapter <TMessage>(_socketService));
            }));

            if (_options.BindType == AddressBindType.Any)
            {
                _channel = await bootstrap.BindAsync(_options.Port);
            }
            else if (_options.BindType == AddressBindType.InternalAddress)
            {
                var localPoint = IPUtility.GetLocalIntranetIP();
                if (localPoint == null)
                {
                    this._logger.LogWarning("there isn't an avaliable internal ip address,the service will be hosted at loopback address.");
                    _channel = await bootstrap.BindAsync(IPAddress.Loopback, _options.Port);
                }
                else
                {
                    //this._logger.LogInformation("TcpServerHost bind at {0}",localPoint);
                    _channel = await bootstrap.BindAsync(localPoint, this._options.Port);
                }
            }
            else if (_options.BindType == AddressBindType.Loopback)
            {
                _channel = await bootstrap.BindAsync(IPAddress.Loopback, _options.Port);
            }
            else
            {
                _channel = await bootstrap.BindAsync(IPAddress.Parse(_options.SpecialAddress), _options.Port);
            }

            Console.Write(_options.StartupWords, _channel.LocalAddress);
        }
        private async Task TestAutoReadOffNoDataReadUntilReadCalled0(ServerBootstrap sb, Bootstrap cb, bool isLibuvServer)
        {
            IChannel  serverChannel = null;
            IChannel  clientChannel = null;
            const int sleepMs       = 100;

            try
            {
                sb.Option(ChannelOption.AutoRead, isLibuvServer); // LibuvServer 不支持 No-AutoRead
                sb.ChildOption(ChannelOption.AutoRead, false);
                cb.Option(ChannelOption.AutoRead, false);
                CountdownEvent             serverReadyLatch          = new CountdownEvent(1);
                CountdownEvent             acceptorReadLatch         = new CountdownEvent(1);
                CountdownEvent             serverReadLatch           = new CountdownEvent(1);
                CountdownEvent             clientReadLatch           = new CountdownEvent(1);
                AtomicReference <IChannel> serverConnectedChannelRef = new AtomicReference <IChannel>();

                sb.Handler(new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddLast(new ChannelInboundHandlerAdapter0(acceptorReadLatch));
                }));

                sb.ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
                {
                    serverConnectedChannelRef.Value = ch;
                    ch.Pipeline.AddLast(new SimpleChannelInboundHandler0(serverReadLatch));
                    serverReadyLatch.SafeSignal();
                }));

                cb.Handler(new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddLast(new SimpleChannelInboundHandler1(clientReadLatch));
                }));

                serverChannel = await sb.BindAsync();

                clientChannel = await cb.ConnectAsync(serverChannel.LocalAddress);

                await clientChannel.WriteAndFlushAsync(clientChannel.Allocator.Buffer().WriteZero(1));

                // The acceptor shouldn't read any data until we call read() below, but give it some time to see if it will.
                if (!isLibuvServer)
                {
                    Thread.Sleep(sleepMs);
                    Assert.Equal(1, acceptorReadLatch.CurrentCount);
                    serverChannel.Read();
                    serverReadyLatch.Wait();
                }

                IChannel serverConnectedChannel = serverConnectedChannelRef.Value;
                Assert.NotNull(serverConnectedChannel);

                // Allow some amount of time for the server peer to receive the message (which isn't expected to happen
                // until we call read() below).
                Thread.Sleep(sleepMs);
                Assert.Equal(1, serverReadLatch.CurrentCount);
                serverConnectedChannel.Read();
                serverReadLatch.Wait();

                // Allow some amount of time for the client to read the echo.
                Thread.Sleep(sleepMs);
                Assert.Equal(1, clientReadLatch.CurrentCount);
                clientChannel.Read();
                clientReadLatch.Wait();
            }
            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)));
            }
        }
Beispiel #11
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            // 主的线程
            this._bossGroup = new MultithreadEventLoopGroup(1);
            // 工作线程,默认根据CPU计算
            this._workerGroup = new MultithreadEventLoopGroup();

            var bootstrap = new ServerBootstrap()
                            .Group(this._bossGroup, this._workerGroup);


            if (this._options.UseLibuv)
            {
                bootstrap.Channel <TcpServerChannel>();
            }
            else
            {
                bootstrap.Channel <TcpServerSocketChannel>();
            }

            bootstrap.Channel <TcpServerSocketChannel>()
            .Option(ChannelOption.SoBacklog, this._options.SoBacklog);     //NOTE: 是否可以公开更多Netty的参数

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                bootstrap
                .Option(ChannelOption.SoReuseport, true)
                .ChildOption(ChannelOption.SoReuseaddr, true);
            }

            bootstrap.Handler(new LoggingHandler("LSTN"))
            .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                var pipeline = channel.Pipeline;

                //TODO:ssl support

                pipeline.AddLast(new LoggingHandler("CONN"));
                var meta = this._protocol.GetProtocolMeta();

                if (meta != null)
                {
                    // IdleStateHandler
                    pipeline.AddLast("timeout", new IdleStateHandler(0, 0, meta.HeartbeatInterval / 1000 * 2));     //服务端双倍来处理

                    //消息前处理
                    pipeline.AddLast(
                        new LengthFieldBasedFrameDecoder(
                            meta.MaxFrameLength,
                            meta.LengthFieldOffset,
                            meta.LengthFieldLength,
                            meta.LengthAdjustment,
                            meta.InitialBytesToStrip
                            )
                        );
                }
                else                                                              //Simple Protocol For Test
                {
                    pipeline.AddLast("timeout", new IdleStateHandler(0, 0, 360)); // heartbeat each 6 second
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
                }

                //收到消息后的解码处理Handler
                pipeline.AddLast(new ChannelDecodeHandler <TMessage>(this._protocol));
                //业务处理Handler,即解码成功后如何处理消息的类
                pipeline.AddLast(new TcpServerChannelHandlerAdapter <TMessage>(this._socketService, this._protocol));
            }));

            if (this._options.BindType == AddressBindType.Any)
            {
                this._channel = await bootstrap.BindAsync(this._options.Port);
            }
            else if (this._options.BindType == AddressBindType.InternalAddress)
            {
                var localPoint = IPUtility.GetLocalIntranetIP();
                //this._logger.LogInformation("TcpServerHost bind at {0}",localPoint);
                this._channel = await bootstrap.BindAsync(localPoint, this._options.Port);
            }
            else if (this._options.BindType == AddressBindType.Loopback)
            {
                this._channel = await bootstrap.BindAsync(IPAddress.Loopback, this._options.Port);
            }
            else
            {
                this._channel = await bootstrap.BindAsync(IPAddress.Parse(this._options.SpecialAddress), this._options.Port);
            }

            Console.Write(this._options.StartupWords, this._channel.LocalAddress);
        }
Beispiel #12
0
        private async Task TestSimpleEcho0(
            ServerBootstrap sb, Bootstrap cb, bool additionalExecutor, bool voidPromise, bool autoRead)
        {
            EchoHandler sh = new EchoHandler(autoRead);
            EchoHandler ch = new EchoHandler(autoRead);

            if (additionalExecutor)
            {
                sb.ChildHandler(new ActionChannelInitializer <IChannel>(c =>
                {
                    c.Pipeline.AddLast(_group, sh);
                }));
                cb.Handler(new ActionChannelInitializer <IChannel>(c =>
                {
                    c.Pipeline.AddLast(_group, ch);
                }));
            }
            else
            {
                sb.ChildHandler(sh);
                sb.Handler(new ChannelHandlerAdapter());
                cb.Handler(ch);
            }
            sb.ChildOption(ChannelOption.AutoRead, autoRead);
            cb.Option(ChannelOption.AutoRead, autoRead);

            IChannel sc = await sb.BindAsync();

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

            for (int i = 0; i < s_data.Length;)
            {
                int         length = Math.Min(s_random.Next(1024 * 64), s_data.Length - i);
                IByteBuffer buf    = Unpooled.WrappedBuffer(s_data, i, length);
                if (voidPromise)
                {
                    Assert.Equal(cc.VoidPromise().Task, cc.WriteAndFlushAsync(buf, cc.VoidPromise()));
                }
                else
                {
                    Assert.NotEqual(cc.VoidPromise().Task, cc.WriteAndFlushAsync(buf));
                }
                i += length;
            }

            while (ch._counter < s_data.Length)
            {
                if (sh._exception.Value != null)
                {
                    break;
                }
                if (ch._exception.Value != null)
                {
                    break;
                }

                Thread.Sleep(50);
            }

            while (sh._counter < s_data.Length)
            {
                if (sh._exception.Value != null)
                {
                    break;
                }
                if (ch._exception.Value != null)
                {
                    break;
                }

                Thread.Sleep(50);
            }

            await sh._channel.CloseAsync();

            await ch._channel.CloseAsync();

            await sc.CloseAsync();

            if (sh._exception.Value != null && !(sh._exception.Value is SocketException || (sh._exception.Value is ChannelException chexc && chexc.InnerException is OperationException) || sh._exception.Value is OperationException))
            {
                throw sh._exception.Value;
            }
            if (ch._exception.Value != null && !(ch._exception.Value is SocketException || (sh._exception.Value is ChannelException chexc1 && chexc1.InnerException is OperationException) || sh._exception.Value is OperationException))
            {
                throw ch._exception.Value;
            }
            if (sh._exception.Value != null)
            {
                throw sh._exception.Value;
            }
            if (ch._exception.Value != null)
            {
                throw ch._exception.Value;
            }
        }