public Task StartAsync(CancellationToken cancellationToken)
        {
            bossGroup   = new DispatcherEventLoopGroup();
            workerGroup = new WorkerEventLoopGroup(bossGroup, 1);
            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)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                using (var scope = serviceProvider.CreateScope())
                {
                    pipeline.AddLast("http_encoder", new HttpResponseEncoder());
                    pipeline.AddLast("http_decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
                    //将多个消息转换为单一的request或者response对象 =>IFullHttpRequest
                    pipeline.AddLast("http_aggregator", new HttpObjectAggregator(int.MaxValue));
                    pipeline.AddLast("http_jt808webapihandler", scope.ServiceProvider.GetRequiredService <JT808WebAPIServerHandler>());
                }
            }));
            logger.LogInformation($"JT808 WebAPI Server start at {IPAddress.Any}:{configuration.WebApiPort}.");
            return(bootstrap.BindAsync(configuration.WebApiPort).ContinueWith(i => bootstrapChannel = i.Result));
        }
Example #2
0
        static async Task RunServerAsync()
        {
            IEventLoopGroup group, workGroup;
            var             dispatcher = new DispatcherEventLoopGroup();

            group     = dispatcher;
            workGroup = new WorkerEventLoopGroup(dispatcher);

            try
            {
                var bootstrap = new ServerBootstrap()
                                .Group(group, workGroup)
                                .Channel <TcpServerChannel>()
                                .Option(ChannelOption.SoBacklog, 8192)
                                .Handler(new LoggingHandler(LogLevel.INFO))
                                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast(new HttpServerCodec());
                    pipeline.AddLast(new HttpObjectAggregator(65536));
                    pipeline.AddLast(new WebSockerServerHandler());
                }));
                IChannel bootstrapChannel = await bootstrap.BindAsync(IPAddress.IPv6Any, 5004);

                Console.WriteLine($"Tcp started. Listening on {bootstrapChannel.LocalAddress}");
                Console.ReadLine();
                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                workGroup.ShutdownGracefullyAsync().Wait();
                group.ShutdownGracefullyAsync().Wait();
            }
        }
        public void Test1()
        {
            // 作为源包转发服务端
            DispatcherEventLoopGroup bossGroup   = new DispatcherEventLoopGroup();
            WorkerEventLoopGroup     workerGroup = new WorkerEventLoopGroup(bossGroup, 1);
            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
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                channel.Pipeline.AddLast("jt808Buffer", new DelimiterBasedFrameDecoder(int.MaxValue,
                                                                                       Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }),
                                                                                       Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag })));
                channel.Pipeline.AddLast("jt808Decode", new JT808ClientDecoder());
            }));
            bootstrap.BindAsync(6655);
            //作为设备上传
            byte[] bytes = "7E 02 00 00 26 12 34 56 78 90 12 00 7D 02 00 00 00 01 00 00 00 02 00 BA 7F 0E 07 E4 F1 1C 00 28 00 3C 00 00 18 10 15 10 10 10 01 04 00 00 00 64 02 02 00 7D 01 13 7E".ToHexBytes();
            SimpleTcpClient.WriteAsync(bytes);
            Thread.Sleep(10000);
            SimpleTcpClient.Down();
        }
Example #4
0
        private DotnettyServer(string etcdHost, int etcdPort)
        {
            EtcdClient = new EtcdClient(etcdHost, etcdPort);
            InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => level == Microsoft.Extensions.Logging.LogLevel.Information, false));
            var dispatcher = new DispatcherEventLoopGroup();

            group           = dispatcher;
            workGroup       = new WorkerEventLoopGroup(dispatcher);
            serverBootstrap = new ServerBootstrap()
                              .Group(group, workGroup)
                              .Channel <TcpServerChannel>()//TcpServerSocketChannel
                              .Option(ChannelOption.SoBacklog, 8192)
                              .Handler(new LoggingHandler(LogLevel.INFO))
                              .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>//ActionChannelInitializer
            {
                IChannelPipeline pipeline = channel.Pipeline;

                //pipeline.AddLast(new DelimiterBasedFrameDecoder(8192,new[]{
                //    Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes("&sup;")),
                //    Unpooled.WrappedBuffer(new[] { (byte)'\r', (byte)'\n' }),
                //    Unpooled.WrappedBuffer(new[] { (byte)'\n' }),
                //}));
                pipeline.AddLast(new DynamicHandler(Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes("&sup;"))));
                //pipeline.AddLast(new TestHandler());
                ////pipeline.AddLast(new HttpRequestDecoder(4096, 8192, 8192, false));
                //pipeline.AddLast(new HttpResponseEncoder());
                //pipeline.AddLast(new StringEncoder());
                ////pipeline.AddLast(new StringDecoder());
                //pipeline.AddLast(new HttpObjectAggregator(1048576));

                ////pipeline.AddLast(new HttpContentCompressor());//压缩
                //pipeline.AddLast(new HttpServerHandler(etcdClient));
            }));
        }
Example #5
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            bossGroup   = new DispatcherEventLoopGroup();
            workerGroup = new WorkerEventLoopGroup(bossGroup, configuration.EventLoopCount);
            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)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast(new TcpHandler(Provider.GetRequiredService <ILogger <TcpHandler> >()));
                var lengthFieldLength = configuration.LengthFieldLength;
                pipeline.AddLast(new LengthFieldBasedFrameDecoder(ByteOrder.BigEndian,
                                                                  configuration.MaxFrameLength, 0, lengthFieldLength, 0, lengthFieldLength, true));
                pipeline.AddLast(new RequestDecoder(decoder), new LengthFieldPrepender(lengthFieldLength), new ResponseEncoder(encoder), handler);
            }));
            logger.LogInformation($"Server start at {IPAddress.Any}:{configuration.Port}.");
            return(bootstrap.BindAsync(configuration.Port)
                   .ContinueWith(i => bootstrapChannel = i.Result));
        }
Example #6
0
        protected override void CreateEventLoop(int eventLoopCount)
        {
            var dispatcher = new DispatcherEventLoop();

            bossGroup   = new MultithreadEventLoopGroup(_ => dispatcher, 1);
            workerGroup = new WorkerEventLoopGroup(dispatcher, eventLoopCount);
        }
Example #7
0
        static async Task RunServerAsync()
        {
            IEventLoopGroup group, workGroup;
            var             dispatcher = new DispatcherEventLoopGroup();

            group     = dispatcher;
            workGroup = new WorkerEventLoopGroup(dispatcher);

            try
            {
                var bootstrap = new ServerBootstrap()
                                .Group(group, workGroup)
                                .Channel <TcpServerChannel>()
                                .Option(ChannelOption.SoBacklog, 8192)
                                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
                    pipeline.AddLast("aggregator", new HttpObjectAggregator(1048576));
                    pipeline.AddLast("deflater", new HttpContentCompressor());                //压缩
                    pipeline.AddLast("encoder", new HttpResponseEncoder());
                    pipeline.AddLast("handler", new HttpServerHandler());
                }));
                IChannel bootstrapChannel = await bootstrap.BindAsync(IPAddress.IPv6Any, 5001);

                Console.WriteLine($"Httpd started. Listening on {bootstrapChannel.LocalAddress}");
                Console.ReadLine();
                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait();
            }
        }
Example #8
0
        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 HttpObjectAggregator(65536));
                using (var scope = serviceProvider.CreateScope())
                {
                    pipeline.AddLast("JT1078WebSocketServerHandler", scope.ServiceProvider.GetRequiredService <JT1078WebSocketServerHandler>());
                }
            }));
            logger.LogInformation($"JT1078 WebSocket Server start at {IPAddress.Any}:{configuration.WebSocketPort}.");
            return(bootstrap.BindAsync(configuration.WebSocketPort)
                   .ContinueWith(i => bootstrapChannel = i.Result));
        }
Example #9
0
        static async Task RunServerAsync()
        {
            IEventLoopGroup group, workGroup;
            var             dispatcher = new DispatcherEventLoopGroup();

            group     = dispatcher;
            workGroup = new WorkerEventLoopGroup(dispatcher);

            try
            {
                var bootstrap = new ServerBootstrap()
                                .Group(group, workGroup)
                                .Channel <TcpServerChannel>()
                                .Option(ChannelOption.SoBacklog, 8192)
                                .Handler(new LoggingHandler(LogLevel.INFO))
                                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes("&sup;"))));
                    pipeline.AddLast(new StringEncoder());
                    pipeline.AddLast(new StringDecoder());
                    pipeline.AddLast(new SocketServerHandler());
                }));
                IChannel bootstrapChannel = await bootstrap.BindAsync(IPAddress.IPv6Any, 5004);

                Console.WriteLine($"Tcp started. Listening on {bootstrapChannel.LocalAddress}");
                Console.ReadLine();
                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                workGroup.ShutdownGracefullyAsync().Wait();
                group.ShutdownGracefullyAsync().Wait();
            }
        }
Example #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IKeyValueCache <string, IChannel>, ChannelCache>();
            // services.AddTransient<LoginHandler>();
            services.AddTransient <PushMessageHandler>();
            services.AddNettyService((services, bootstrap) =>
            {
                /// <summary>
                ///
                /// </summary>
                var dispatcher    = new DispatcherEventLoopGroup();
                var bossGroup     = dispatcher;
                var workGroup     = new WorkerEventLoopGroup(dispatcher);
                var businessGroup = new EventLoopGroup();
                bootstrap.Group(bossGroup, workGroup);

                /// 具体个选项的作用:https://blog.csdn.net/zuixiaoyao_001/article/details/90198968
                bootstrap.Channel <TcpServerChannel>();
                bootstrap.Option(ChannelOption.SoBacklog, 128);                                 //  处理客户端连接的队列大小
                bootstrap.Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(500)); // 连接超时时间
                bootstrap.Option(ChannelOption.SoReuseaddr, true);                              // 允许重复使用本地地址和端口
                bootstrap.Option(ChannelOption.SoKeepalive, true);                              // 如果在两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文

                bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    var pipeline = channel.Pipeline;
                    pipeline.AddLast("ACCEPT-LOG", new LoggingHandler());
                    // pipeline.AddLast("ACCEPT-CONN", services.GetRequiredService<LoginHandler>());
                }));

                bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    var pipeline = channel.Pipeline;
                    pipeline.AddLast(new ProtobufVarint32FrameDecoder());
                    pipeline.AddLast(new ProtobufDecoder(Options.Parser));
                    pipeline.AddLast(new ProtobufVarint32LengthFieldPrepender());
                    pipeline.AddLast(new ProtobufEncoder());

                    pipeline.AddLast(businessGroup, services.GetRequiredService <PushMessageHandler>());
                }));
            });

            services.AddTransient <BaseDataUpdateService>();

            services.AddMqClient("RabbitMq", Configuration);
            services.AddMqConsumerService((serviceProvider, mqClient) =>
            {
                mqClient.ReceiveCommand <BaseDataUpdateCommand>(queue: string.Empty, resolve: () => serviceProvider.GetRequiredService <BaseDataUpdateService>().Handle, prefetchCount: 10);
            });

            services.AddMemoryCache();
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "NettyDemo", Version = "v1"
                });
            });
        }
        /// <summary>
        /// start as an asynchronous operation.
        /// </summary>
        /// <param name="endPoint">The end point.</param>
        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();

            if (AppConfig.ServerOptions.Libuv)
            {
                var dispatcher = new DispatcherEventLoopGroup();
                bossGroup   = dispatcher;
                workerGroup = new WorkerEventLoopGroup(dispatcher);
                bootstrap.Channel <TcpServerChannel>();
            }
            else
            {
                bossGroup   = new MultithreadEventLoopGroup(1);
                workerGroup = new MultithreadEventLoopGroup();
                bootstrap.Channel <TcpServerSocketChannel>();
            }

            bootstrap
            .Option(ChannelOption.SoBacklog, AppConfig.ServerOptions.SoBacklog)
            .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.Information))
                {
                    _logger.LogInformation($"服务主机启动成功,监听地址:{endPoint}。");
                }
            }
            catch
            {
                _logger.LogError($"服务主机启动失败,监听地址:{endPoint}。 ");
            }
        }
Example #12
0
        protected override void SetupServerBootstrap(ServerBootstrap bootstrap)
        {
            var dispatcher = new DispatcherEventLoopGroup();
            var bossGroup  = dispatcher;
            var workGroup  = new WorkerEventLoopGroup(dispatcher);

            bootstrap.Group(bossGroup, workGroup)
            .Channel <TcpServerChannel>();
        }
Example #13
0
        /// <summary>
        /// start as an asynchronous operation.
        /// </summary>
        /// <param name="endPoint">The end point.</param>
        public async Task StartAsync(EndPoint endPoint)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug($"准备启动Mqtt服务主机,监听地址:{endPoint}。");
            }
            IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1);
            IEventLoopGroup
                workerGroup =
                new MultithreadEventLoopGroup();     //Default eventLoopCount is Environment.ProcessorCount * 2
            var bootstrap = new ServerBootstrap();

            if (AppConfig.ServerOptions.Libuv)
            {
                var dispatcher = new DispatcherEventLoopGroup();
                bossGroup   = dispatcher;
                workerGroup = new WorkerEventLoopGroup(dispatcher);
                bootstrap.Channel <TcpServerChannel>();
            }
            else
            {
                bossGroup   = new MultithreadEventLoopGroup(1);
                workerGroup = new MultithreadEventLoopGroup();
                bootstrap.Channel <TcpServerSocketChannel>();
            }

            bootstrap
            .Option(ChannelOption.SoBacklog, AppConfig.ServerOptions.SoBacklog)
            .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
            .Group(bossGroup, workerGroup)
            .Option(ChannelOption.TcpNodelay, true)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                var pipeline = channel.Pipeline;
                pipeline.AddLast(MqttEncoder.Instance,
                                 new MqttDecoder(true, 256 * 1024), new ServerHandler(async(context, packetType, message) =>
                {
                    var mqttHandlerService =
                        new ServerMqttHandlerService(_logger, _channelService, _mqttBehaviorProvider);
                    await ChannelWrite(context, message, packetType, mqttHandlerService);
                }, _logger, _channelService, _mqttBehaviorProvider));
            }));
            try
            {
                _channel = await bootstrap.BindAsync(endPoint);

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation($"Mqtt服务主机启动成功,监听地址:{endPoint}。");
                }
            }
            catch
            {
                _logger.LogError($"Mqtt服务主机启动失败,监听地址:{endPoint}。 ");
            }
        }
Example #14
0
        protected override void SetupServerBootstrap(ServerBootstrap bootstrap)
        {
            var dispatcher = new DispatcherEventLoopGroup();
            var bossGroup  = dispatcher;
            var workGroup  = new WorkerEventLoopGroup(dispatcher);

            bootstrap.Group(bossGroup, workGroup)
            .Channel <TcpServerChannel>();
            //bootstrap.Handler(new DotNetty.Handlers.Logging.LoggingHandler("LSTN"));
        }
Example #15
0
        public async Task StartAsync(EndPoint endPoint)
        {
            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();//Default eventLoopCount is Environment.ProcessorCount * 2
            var             bootstrap   = new ServerBootstrap();

            if (AppConfig.ServerOptions.Libuv)
            {
                var dispatcher = new DispatcherEventLoopGroup();
                bossGroup   = dispatcher;
                workerGroup = new WorkerEventLoopGroup(dispatcher);
                bootstrap.Channel <TcpServerChannel>();
            }
            else
            {
                bossGroup   = new MultithreadEventLoopGroup(1);
                workerGroup = new MultithreadEventLoopGroup();
                bootstrap.Channel <TcpServerSocketChannel>();
            }
            bootstrap
            .Option(ChannelOption.SoBacklog, AppConfig.ServerOptions.SoBacklog)
            .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));
                if (AppConfig.ServerOptions.EnableHealthCheck)
                {
                    pipeline.AddLast(new IdleStateHandler(AppConfig.ServerOptions.HealthCheckWatchIntervalInSeconds * 2, 0, 0));
                    pipeline.AddLast(new ChannelInboundHandlerAdapter());
                }
                pipeline.AddLast(DotNettyConstants.TransportMessageAdapterName, 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);

                _logger.LogInformation($"Rpc服务主机(Tcp协议){AppConfig.ServerOptions.HostName}启动成功,RPC服务地址:{endPoint}.");
            }
            catch (Exception ex)
            {
                _logger.LogError($"Rpc服务主机(Tcp协议){AppConfig.ServerOptions.HostName}启动失败,原因:{ex.Message},RPC服务地址:{endPoint}.");
                throw ex;
            }
        }
Example #16
0
        private void InitializeNetty()
        {
            var dispatcher = new DispatcherEventLoopGroup();

            _bossGroup   = dispatcher;
            _workerGroup = new WorkerEventLoopGroup(dispatcher);

            _bootstrap = new ServerBootstrap()
                         .Group(_bossGroup, _workerGroup)
                         .Channel <TcpServerChannel>()
                         .Option(ChannelOption.SoBacklog, 100)
                         .ChildHandler(new ActionChannelInitializer <IChannel>(_setting.ChannelAction));
        }
Example #17
0
        static async Task RunServerAsync()
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            }

            Console.WriteLine($"Server garbage collection: {GCSettings.IsServerGC}");
            Console.WriteLine($"Current latency mode for garbage collection: {GCSettings.LatencyMode}");

            IEventLoopGroup group;
            IEventLoopGroup workGroup;
            var             dispatcher = new DispatcherEventLoopGroup();

            group     = dispatcher;
            workGroup = new WorkerEventLoopGroup(dispatcher);
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(group, workGroup);
                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)
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    //pipeline.AddLast("encoder", new HttpResponseEncoder());
                    pipeline.AddLast(new HttpServerCodec());
                    pipeline.AddLast(new HttpObjectAggregator(ConfigHelper.GetValue <int>("maxContentLength")));
                    pipeline.AddLast("handler", new HttpServerHandler());
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(IPAddress.IPv6Any, ConfigHelper.GetValue <int>("httpPort"));

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

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait();
            }
        }
        /// <summary>
        /// 需要使用 SocketTool 创建tcp服务器
        /// </summary>
        public JT808SourcePackageChannelServiceTest()
        {
            SimpleTcpClient = new JT808SimpleTcpClient(endPoint, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6555));
            //作为设备5秒上传
            Task.Run(() =>
            {
                Random random = new Random();
                while (true)
                {
                    JT808Package jT808Package = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("12345678900" + random.Next(0, 2).ToString());
                    SimpleTcpClient.WriteAsync(JT808Serializer.Serialize(jT808Package));
                    Thread.Sleep(1000);
                }
            });

            // 作为源包转发服务端
            DispatcherEventLoopGroup bossGroup   = new DispatcherEventLoopGroup();
            WorkerEventLoopGroup     workerGroup = new WorkerEventLoopGroup(bossGroup, 1);
            ServerBootstrap          bootstrap   = new ServerBootstrap();

            bootstrap.Group(bossGroup, workerGroup);
            bootstrap.Channel <TcpServerChannel>();
            bootstrap
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                channel.Pipeline.AddLast("jt808Buffer", new DelimiterBasedFrameDecoder(int.MaxValue,
                                                                                       Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }),
                                                                                       Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag })));
                channel.Pipeline.AddLast("jt808Decode", new JT808ClientDecoder());
            }));
            bootstrap.BindAsync(6655);

            DispatcherEventLoopGroup bossGroup1   = new DispatcherEventLoopGroup();
            WorkerEventLoopGroup     workerGroup1 = new WorkerEventLoopGroup(bossGroup1, 1);
            ServerBootstrap          bootstrap1   = new ServerBootstrap();

            bootstrap1.Group(bossGroup1, workerGroup1);
            bootstrap1.Channel <TcpServerChannel>();
            bootstrap1
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                channel.Pipeline.AddLast("jt808Buffer", new DelimiterBasedFrameDecoder(int.MaxValue,
                                                                                       Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }),
                                                                                       Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag })));
                channel.Pipeline.AddLast("jt808Decode", new JT808ClientDecoder());
            }));
            bootstrap1.BindAsync(6656);
        }
Example #19
0
        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, configuration.SoBacklog)
            .ChildOption(ChannelOption.Allocator, serverBufferAllocator)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                using (var scope = serviceProvider.CreateScope())
                {
                    channel.Pipeline.AddLast("systemIdleState", new IdleStateHandler(
                                                 configuration.ReaderIdleTimeSeconds,
                                                 configuration.WriterIdleTimeSeconds,
                                                 configuration.AllIdleTimeSeconds));
                    channel.Pipeline.AddLast("jtneTcpConnection", scope.ServiceProvider.GetRequiredService <JTNETcpConnectionHandler>());
                    //LengthFieldBasedFrameDecoder 定长解码器
                    //参数说明:
                    //maxFrameLength:解码的帧的最大长度
                    //lengthFieldOffset:长度字段的偏差(长度属性的起始位(偏移位),包中存放有整个大数据包长度的字节,这段字节的其实位置)
                    //lengthFieldLength:长度字段占的字节数(即存放整个大数据包长度的字节所占的长度)
                    //lengthAdjustmen:添加到长度字段的补偿值(长度调节值,在总长被定义为包含包头长度时,修正信息长度)。
                    //initialBytesToStrip:从解码帧中第一次去除的字节数(跳过的字节数,根据需要我们跳过lengthFieldLength个字节,以便接收端直接接受到不含“长度属性”的内容)
                    //failFast :为true,当frame长度超过maxFrameLength时立即报TooLongFrameException异常,为false,读取完整个帧再报异常
                    //22 JTNEPackage数据体长度
                    //2  JTNEPackage数据体长度占两个字节
                    //1  JTNEPackage校验位
                    channel.Pipeline.AddLast("jtneTcpDecoder", new LengthFieldBasedFrameDecoder(int.MaxValue, 22, 2, 1, 0));
                    channel.Pipeline.AddLast("jtneTcpBuffer", scope.ServiceProvider.GetRequiredService <JTNETcpDecoder>());
                    channel.Pipeline.AddLast("jtneTcpServerHandler", scope.ServiceProvider.GetRequiredService <JTNETcpServerHandler>());
                }
            }));
            logger.LogInformation($"JTNE TCP Server start at {IPAddress.Any}:{configuration.TcpPort}.");
            return(bootstrap.BindAsync(configuration.TcpPort)
                   .ContinueWith(i => bootstrapChannel = i.Result));
        }
Example #20
0
        private static async Task RunServerAsync()
        {
            InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => true, false));

            var dispatcher  = new DispatcherEventLoopGroup();
            var bossGroup   = dispatcher;
            var workerGroup = new WorkerEventLoopGroup(dispatcher);

            var bootstrap = new ServerBootstrap();

            try
            {
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler("SRV-LSTN"))
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    var pipeline = channel.Pipeline;

                    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("mqtt-encoder", new MqttEncoder());
                    //pipeline.AddLast("mqtt-decoder", new MqttDecoder(true, 256 * 1024));
                    //pipeline.AddLast("string-encoder", new StringEncoder());
                    //pipeline.AddLast("string-decoder", new StringDecoder());
                    pipeline.AddLast("request-encoder", new RequestEncoder());
                    pipeline.AddLast("request-decoder", new RequestDecoder());
                    pipeline.AddLast("echo", new EchoServerHandler());
                }));

                var boundChannel = await bootstrap.BindAsync(9998);

                Console.ReadLine();

                await boundChannel.CloseAsync();
            }
            finally
            {
                await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(1))
                    );
            }
        }
        public void Test1()
        {
            //预热
            Thread.Sleep(3000);

            jT808SourcePackageChannelService = ServiceProvider.GetService <JT808SourcePackageChannelService>();
            var result = jT808SourcePackageChannelService.GetAll();

            //创建服务
            DispatcherEventLoopGroup bossGroup2   = new DispatcherEventLoopGroup();
            WorkerEventLoopGroup     workerGroup2 = new WorkerEventLoopGroup(bossGroup2, 1);
            ServerBootstrap          bootstrap2   = new ServerBootstrap();

            bootstrap2.Group(bossGroup2, workerGroup2);
            bootstrap2.Channel <TcpServerChannel>();
            bootstrap2
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                channel.Pipeline.AddLast("jt808Buffer", new DelimiterBasedFrameDecoder(int.MaxValue,
                                                                                       Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }),
                                                                                       Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag })));
                channel.Pipeline.AddLast("jt808Decode", new JT808ClientDecoder());
            }));
            bootstrap2.BindAsync(6522);

            //添加服务
            var addResult = jT808SourcePackageChannelService.Add(new Dtos.JT808IPAddressDto
            {
                Host = "127.0.0.1",
                Port = 6522
            }).Result;

            Thread.Sleep(1000);

            var result1 = jT808SourcePackageChannelService.GetAll();

            //删除
            var result2 = jT808SourcePackageChannelService.Remove(new Dtos.JT808IPAddressDto
            {
                Host = "127.0.0.1",
                Port = 6522
            }).Result;
            //[::ffff:127.0.0.1]:13196
            var result3 = jT808SourcePackageChannelService.GetAll();
        }
Example #22
0
        static async Task RunServerAsync()
        {
            IEventLoopGroup bossGroup;
            IEventLoopGroup workerGroup;

            var dispatcher = new DispatcherEventLoopGroup();

            bossGroup   = dispatcher;
            workerGroup = new WorkerEventLoopGroup(dispatcher);


            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup);
                bootstrap.Channel <TcpServerChannel>();

                bootstrap
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler("SRV-LSTN"))
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    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 SocketServerHandler());
                }));

                IChannel boundChannel = await bootstrap.BindAsync(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)));
            }
        }
Example #23
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));
        }
        public EventLoopGroups(ServerConfiguration serverConfiguration)
        {
            IEventLoopGroup bossGroup;
            IEventLoopGroup workGroup;

            if (serverConfiguration.Libuv)
            {
                var dispatcher = new DispatcherEventLoopGroup();
                bossGroup = dispatcher;
                workGroup = new WorkerEventLoopGroup(dispatcher);
            }
            else
            {
                bossGroup = new MultithreadEventLoopGroup(1);
                workGroup = new MultithreadEventLoopGroup();
            }

            BossGroup   = bossGroup;
            WorkerGroup = workGroup;
        }
        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));
        }
        private ServerBootstrap CreateServerBootstrap(bool useLibuv,
                                                      out IEventLoopGroup bossGroup, out IEventLoopGroup workerGroup)
        {
            Logger.LogInformation(
                $"\n{RuntimeInformation.OSArchitecture} {RuntimeInformation.OSDescription}"
                + $"\n{RuntimeInformation.ProcessArchitecture} {RuntimeInformation.FrameworkDescription}"
                + $"\nProcessor Count : {Environment.ProcessorCount}\n");

            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            }

            Logger.LogDebug($"Server garbage collection: {GCSettings.IsServerGC}");
            Logger.LogDebug($"Current latency mode for garbage collection: {GCSettings.LatencyMode}");
            Logger.LogDebug("\n");

            if (useLibuv)
            {
                var dispatcher = new DispatcherEventLoopGroup();
                bossGroup   = dispatcher;
                workerGroup = new WorkerEventLoopGroup(dispatcher);
            }
            else
            {
                bossGroup   = new MultithreadEventLoopGroup(1);
                workerGroup = new MultithreadEventLoopGroup();
            }
            Logger.LogDebug("Transport type: " + (useLibuv ? "Libuv" : "Socket"));

            var bootstrap = new ServerBootstrap().Group(bossGroup, workerGroup);

            Logger.LogDebug($"Use boss group: {bossGroup.GetType().GetDisplayNameWithNamespace()}");
            Logger.LogDebug($"Use worker group: {workerGroup.GetType().GetDisplayNameWithNamespace()}");

            return(bootstrap);
        }
Example #27
0
        public async Task StartAsync()
        {
            DispatcherEventLoopGroup bossGroup   = new DispatcherEventLoopGroup();
            WorkerEventLoopGroup     workerGroup = new WorkerEventLoopGroup(bossGroup, 4);

            try
            {
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup)
                .Channel <TcpServerChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler("SRV-LSTN"))
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast(new LoggingHandler("SRV-CONN"));

                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(4));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));

                    pipeline.AddLast(new ReadServerMessageChannelHandler(_serializer, _logger));
                    pipeline.AddLast("echo", new RpcServerHandler(async(context, message) =>
                    {
                        await OnReceived(context, message);
                    }));
                }));

                _channel = await bootstrap.BindAsync(_address.CreateEndPoint());

                _logger.Info("服务器启动成功");
            }
            catch (Exception e)
            {
                _logger.Error($"错误日志: {e.Message}", e);
            }
        }
Example #28
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

            Console.WriteLine(
                $"\n{RuntimeInformation.OSArchitecture} {RuntimeInformation.OSDescription}"
                + $"\n{RuntimeInformation.ProcessArchitecture} {RuntimeInformation.FrameworkDescription}"
                + $"\nProcessor Count : {Environment.ProcessorCount}\n");

            bool useLibuv = ServerSettings.UseLibuv;

            Console.WriteLine("Transport type : " + (useLibuv ? "Libuv" : "Socket"));

            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            }

            Console.WriteLine($"Server garbage collection : {(GCSettings.IsServerGC ? "Enabled" : "Disabled")}");
            Console.WriteLine($"Current latency mode for garbage collection: {GCSettings.LatencyMode}");
            Console.WriteLine("\n");

            IEventLoopGroup bossGroup;
            IEventLoopGroup workGroup;
            IEventLoopGroup bossGroup2 = null;
            IEventLoopGroup workGroup2 = null;

            if (useLibuv)
            {
                var dispatcher = new DispatcherEventLoopGroup();
                bossGroup = dispatcher;
                workGroup = new WorkerEventLoopGroup(dispatcher);

                dispatcher = new DispatcherEventLoopGroup();
                bossGroup2 = dispatcher;
                workGroup2 = new WorkerEventLoopGroup(dispatcher);
            }
            else
            {
                bossGroup = new MultithreadEventLoopGroup(1);
                workGroup = new MultithreadEventLoopGroup();
            }

            IChannel http2Channel = null;
            IChannel httpChannel  = null;

            try
            {
                Http2Server http2 = useLibuv ? new Http2Server(bossGroup2, workGroup2) : new Http2Server(bossGroup, workGroup);
                http2Channel = await http2.StartAsync();

                Console.WriteLine("Open your web browser and navigate to " + "http://127.0.0.1:" + HttpServer.PORT);
                HttpServer http = new HttpServer(bossGroup, workGroup);
                httpChannel = await http.StartAsync();

                Console.WriteLine("按任意键退出");
                Console.ReadKey();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.ToString());
                Console.ReadKey();
            }
            finally
            {
                if (http2Channel != null)
                {
                    await http2Channel.CloseAsync();
                }
                if (httpChannel != null)
                {
                    await httpChannel.CloseAsync();
                }

                if (workGroup2 != null)
                {
                    await workGroup2.ShutdownGracefullyAsync();
                }
                if (bossGroup2 != null)
                {
                    await bossGroup2.ShutdownGracefullyAsync();
                }
                await workGroup.ShutdownGracefullyAsync();

                await bossGroup.ShutdownGracefullyAsync();
            }
        }
Example #29
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

            Console.WriteLine(
                $"\n{RuntimeInformation.OSArchitecture} {RuntimeInformation.OSDescription}"
                + $"\n{RuntimeInformation.ProcessArchitecture} {RuntimeInformation.FrameworkDescription}"
                + $"\nProcessor Count : {Environment.ProcessorCount}\n");

            bool useLibuv = ServerSettings.UseLibuv;

            Console.WriteLine($"Transport type : {(useLibuv ? "Libuv" : "Socket")}");

            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            }

            Console.WriteLine($"Server garbage collection : {(GCSettings.IsServerGC ? "Enabled" : "Disabled")}");
            Console.WriteLine($"Current latency mode for garbage collection: {GCSettings.LatencyMode}");
            Console.WriteLine("\n");

            IEventLoopGroup bossGroup;
            IEventLoopGroup workGroup;

            if (useLibuv)
            {
                var dispatcher = new DispatcherEventLoopGroup();
                bossGroup = dispatcher;
                workGroup = new WorkerEventLoopGroup(dispatcher);
            }
            else
            {
                bossGroup = new MultithreadEventLoopGroup(1);
                workGroup = new MultithreadEventLoopGroup();
            }

            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
            }

            try
            {
                int      port             = ServerSettings.Port;
                IChannel bootstrapChannel = null;

                var bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workGroup);

                if (useLibuv)
                {
                    bootstrap.Channel <TcpServerChannel>();
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                        RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    {
                        bootstrap
                        .Option(ChannelOption.SoReuseport, true)
                        .ChildOption(ChannelOption.SoReuseaddr, true);
                    }
                }
                else
                {
                    bootstrap.Channel <TcpServerSocketChannel>();
                }

                bootstrap
                .Option(ChannelOption.SoBacklog, 8192)
                .Handler(new LoggingHandler("LSTN"))
                //.Handler(new ServerChannelRebindHandler(DoBind))
                .ChildHandler(new Http2ServerInitializer(tlsCertificate));

                bootstrapChannel = await bootstrap.BindAsync(IPAddress.Loopback, port);

                //async void DoBind()
                //{
                //    await bootstrapChannel.CloseAsync();
                //    Console.WriteLine("rebind......");
                //    var ch = await bootstrap.BindAsync(IPAddress.Loopback, port);
                //    Console.WriteLine("rebind complate");
                //    Interlocked.Exchange(ref bootstrapChannel, ch);
                //}

                Console.WriteLine("Open your HTTP/2-enabled web browser and navigate to " +
                                  (ServerSettings.IsSsl ? "https" : "http") + "://127.0.0.1:" + ServerSettings.Port + '/');

                Console.WriteLine("Press any key to exit");
                Console.ReadKey();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                await Task.WhenAll(
                    workGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))
                    );
            }
        }
Example #30
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

            Console.WriteLine(
                $"\n{RuntimeInformation.OSArchitecture} {RuntimeInformation.OSDescription}"
                + $"\n{RuntimeInformation.ProcessArchitecture} {RuntimeInformation.FrameworkDescription}"
                + $"\nProcessor Count : {Environment.ProcessorCount}\n");


            bool useLibuv = ServerSettings.UseLibuv;

            Console.WriteLine($"Transport type : {(useLibuv ? "Libuv" : "Socket")}");

            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            }

            Console.WriteLine($"Server garbage collection: {GCSettings.IsServerGC}");
            Console.WriteLine($"Current latency mode for garbage collection: {GCSettings.LatencyMode}");

            IEventLoopGroup group;
            IEventLoopGroup workGroup;

            if (useLibuv)
            {
                var dispatcher = new DispatcherEventLoopGroup();
                group     = dispatcher;
                workGroup = new WorkerEventLoopGroup(dispatcher);
            }
            else
            {
                group     = new MultithreadEventLoopGroup(1);
                workGroup = 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(group, workGroup);

                if (useLibuv)
                {
                    bootstrap.Channel <TcpServerChannel>();
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                        RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    {
                        bootstrap
                        .Option(ChannelOption.SoReuseport, true)
                        .ChildOption(ChannelOption.SoReuseaddr, true);
                    }
                }
                else
                {
                    bootstrap.Channel <TcpServerSocketChannel>();
                }

                bootstrap
                .Option(ChannelOption.SoBacklog, 200)
#if DEBUG
                .Handler(new LoggingHandler("LSTN"))
#endif
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                    }
#if DEBUG
                    pipeline.AddLast(new LoggingHandler("CONN"));
#endif
                    //pipeline.AddLast("encoder", new HttpResponseEncoder());
                    //pipeline.AddLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
                    pipeline.AddLast(new HttpServerCodec(4096, 8192, 8192, false));

                    //pipeline.AddLast(new HttpObjectAggregator(65536));

                    pipeline.AddLast(new HttpServerExpectContinueHandler());

                    pipeline.AddLast("handler", new HelloServerHandler());
                }));

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

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

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait();
            }
        }