示例#1
0
        public void Start()
        {
            try
            {
                _bootstrap.Group(_bossGroup, _workerGroup);
                _bootstrap.Channel <TcpServerSocketChannel>();
                _bootstrap.Option(ChannelOption.SoBacklog, 100);
                _bootstrap.ChildOption(ChannelOption.SoKeepalive, true);
                _bootstrap.Option(ChannelOption.TcpNodelay, true);
                _bootstrap.Option(ChannelOption.SoReuseport, true);
                _bootstrap.ChildOption(ChannelOption.SoReuseport, true);
                _bootstrap.Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default);
                _bootstrap.ChildOption(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default);
                _bootstrap.ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast("DotNetty-enc", new LengthFieldPrepender(4));
                    pipeline.AddLast("DotNetty-dec", new LengthFieldBasedFrameDecoder(GlobalConfig.Config.MaxFrameLength, 0, 4, 0, 4));
                    pipeline.AddLast(new MasterMessageHandler((IChannelMessageHandler)this));
                }));

                _bootstrapChannel = _bootstrap.BindAsync(_localPort).Result;
                Logger.Log.Info(false, "主节点侦听端口:" + GlobalConfig.Config.MasterListenPort);
            }
            catch (Exception ex)
            {
                Logger.Log.Error(true, "", ex);
            }
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            IPAddress ip_address = IPAddress.Parse(_config.GetSection("GatewayConfig")["websocket_ip_address"]);
            int       port       = int.Parse(_config.GetSection("GatewayConfig")["websocket_port"]);
            var       dispatcher = new DispatcherEventLoopGroup();

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

            _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;
                pipeline.AddLast(new HttpServerCodec());
                pipeline.AddLast(new HttpObjectAggregator(65536));
                pipeline.AddLast(new WebSocketChannelHandler(_client, _loggerFactory, _config));
            }));

            _bootstrapChannel = await _bootstrap.BindAsync(ip_address, port);

            _logger.LogInformation($"Websocket服务启动成功 {ip_address}:{port}");
        }
示例#3
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));
        }
示例#4
0
        private void Initialize()
        {
            if (Initializer == null)
            {
                Out.QuickLog("Abstract server failed to start on Port " + Port + " due to the server's initializer being NULL");
                return;
            }

            _bootstrap.Group(_bossEventLoopGroup,
                             _workerEventLoopGroup);

            // Set Channel Type to Tcp.
            _bootstrap.Channel <TcpServerSocketChannel>();

            // Set Server Options
            _bootstrap.Option(ChannelOption.SoLinger, 0);
            _bootstrap.Option(ChannelOption.SoBacklog, Backlog);

            _bootstrap.ChildHandler(Initializer);

            _bootstrap.ChildOption(ChannelOption.SoLinger, 0);
            _bootstrap.ChildOption(ChannelOption.SoKeepalive, true);
            _bootstrap.ChildOption(ChannelOption.TcpNodelay, true);
            _bootstrap.ChildOption(ChannelOption.SoReuseaddr, true);
        }
示例#5
0
        private ServerBootstrap MakeBootStrap()
        {
            var bootstrap = new ServerBootstrap();

            bootstrap.Group(this.bossGroup, this.workGroup)
            .Channel <TcpServerChannel>();

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

            bootstrap
            .Option(ChannelOption.SoBacklog, this.config.SoBackLog)
            .Option(ChannelOption.SoRcvbuf, this.config.RecvWindowSize)
            .Option(ChannelOption.SoSndbuf, this.config.SendWindowSize)
            .Option(ChannelOption.SoReuseaddr, true)
            .Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
            .ChildOption(ChannelOption.TcpNodelay, true)
            .ChildOption(ChannelOption.SoKeepalive, true)
            .ChildOption(ChannelOption.WriteBufferHighWaterMark, this.config.WriteBufferHighWaterMark)
            .ChildOption(ChannelOption.WriteBufferLowWaterMark, this.config.WriteBufferLowWaterMark);

            return(bootstrap);
        }
        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));
        }
示例#7
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));
        }
示例#8
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
            {
            }
        }
        static async Task RunServerAsync()
        {
            bossGroup   = new MultithreadEventLoopGroup(1);
            workerGroup = new MultithreadEventLoopGroup();
            try {
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap.Option(ChannelOption.SoKeepalive, true);
                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("echo", new EchoServerHandler());
                }));

                boundChannel = await bootstrap.BindAsync(9001);

                //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)));
            }
        }
示例#10
0
        private ServerBootstrap ServerFactory()
        {
            X509Certificate2 tlsCertificate = null;

            if (_isSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{_pfx}.pfx"), _pwd);
            }

            var addressFamily = Settings.DnsUseIpv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;

            var server = new ServerBootstrap()
                         .Group(_serverEventLoopGroup)
                         .Option(ChannelOption.SoReuseaddr, Settings.TcpReuseAddr)
                         .Option(ChannelOption.SoKeepalive, Settings.TcpKeepAlive)
                         .Option(ChannelOption.TcpNodelay, Settings.TcpNoDelay)
                         .Option(ChannelOption.AutoRead, true)
                         .Option(ChannelOption.SoBacklog, Settings.Backlog)
                         .Option(ChannelOption.Allocator, Settings.EnableBufferPooling ? (IByteBufferAllocator)PooledByteBufferAllocator.Default : UnpooledByteBufferAllocator.Default)
                         .ChannelFactory(() => Settings.EnforceIpFamily
                    ? new TcpServerSocketChannel(addressFamily)
                    : new TcpServerSocketChannel())
                         .ChildHandler(new ActionChannelInitializer <TcpSocketChannel>((channel =>
            {
                var pipeline = channel.Pipeline;

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

                //pipeline.AddLast(new DotNetty.Handlers.Logging.LoggingHandler("SRV-CONN"));
                //pipeline.AddLast(new LengthFieldPrepender(4));
                //pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));
                pipeline.AddLast(new NettyLoggingHandler());
                SetInitialChannelPipeline(channel);
                //pipeline.AddLast(_channelHandlers?.ToArray());
                pipeline.AddLast(new ServerHandler(this, _service));
            })));

            if (Settings.ReceiveBufferSize.HasValue)
            {
                server.Option(ChannelOption.SoRcvbuf, Settings.ReceiveBufferSize.Value);
            }
            if (Settings.SendBufferSize.HasValue)
            {
                server.Option(ChannelOption.SoSndbuf, Settings.SendBufferSize.Value);
            }
            if (Settings.WriteBufferHighWaterMark.HasValue)
            {
                server.Option(ChannelOption.WriteBufferHighWaterMark, Settings.WriteBufferHighWaterMark.Value);
            }
            if (Settings.WriteBufferLowWaterMark.HasValue)
            {
                server.Option(ChannelOption.WriteBufferLowWaterMark, Settings.WriteBufferLowWaterMark.Value);
            }

            return(server);
        }
        public async Task StartAsync(EndPoint endPoint)
        {
            Environment.SetEnvironmentVariable("io.netty.allocator.numDirectArenas", "0");

            var bootstrap = new ServerBootstrap();

            if (AppConfig.Option.DisablePooled)
            {
                bootstrap = bootstrap.Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default);
            }
            var bossGroup   = new MultithreadEventLoopGroup();
            var workerGroup = new MultithreadEventLoopGroup();

            bootstrap.Channel <TcpServerSocketChannel>();
            bootstrap
            .Option(ChannelOption.SoBacklog, 128)
            .ChildOption(ChannelOption.SoKeepalive, true)
            .Group(bossGroup)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                var pipeline = channel.Pipeline;
                pipeline.AddLast(new ConnectionChannelHandlerAdapter(_logger));
                pipeline.AddLast(new HandShakeDecoder());
                pipeline.AddLast(new ChunkDecoder());
                pipeline.AddLast(new ChunkEncoder());
                pipeline.AddLast(workerGroup, new RtmpMessageHandler(_mediaStreamDic, async(contenxt, key, message) =>
                {
                    var dic = new Dictionary <StreamName, AbstractRtmpMessage>();
                    dic.Add(key, message);
                    await OnReceived(null, new TransportMessage(dic));
                    message = null;
                }, new RtmpConfig
                {
                    App             = AppConfig.Option.RouteTemplate,
                    IsSaveFlvFile   = AppConfig.Option.IsSaveFlvFile,
                    SaveFlvFilePath = AppConfig.Option.SaveFlvFilePath
                }));
            }));
            try
            {
                _channel = await bootstrap.BindAsync(endPoint);

                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug($"Rtmp服务主机启动成功,监听地址:{endPoint}。");
                }
            }
            catch
            {
                _logger.LogError($"Rtmp服务主机启动失败,监听地址:{endPoint}。 ");
            }
        }
示例#12
0
 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);
 }
示例#13
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();
            }
        }
示例#14
0
 void Bootstrap()
 {
     bootstrap.Group(parentEventLoopGroup, eventLoopGroup);
     bootstrap.Option(ChannelOption.SoBacklog, ListenBacklogSize);
     bootstrap.ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default);
     bootstrap.Channel <TcpServerSocketChannel>();
     bootstrap.Option(ChannelOption.ConnectTimeout, DefaultConnectionIdleTimeout);
     bootstrap.ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
     {
         IChannelPipeline pipeline = channel.Pipeline;
         pipeline.AddLast(new LengthFieldBasedFrameDecoder(ByteOrder.BigEndian, 4096, 1, 4, -5, 0, true));
         pipeline.AddLast(new BmpDecoder(), new BmpMessageHandler());
     }));
 }
示例#15
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));
        }
示例#16
0
        public async Task RunServerAsync()
        {
            BossGroup   = new MultithreadEventLoopGroup();
            WorkerGroup = new MultithreadEventLoopGroup();

            ServerBootstrap = new ServerBootstrap();
            ServerBootstrap.Group(BossGroup, WorkerGroup);
            ServerBootstrap.Channel <TcpServerSocketChannel>();

            ServerBootstrap
            .Option(ChannelOption.SoBacklog, 100)
            .Option(ChannelOption.TcpNodelay, true)
            .Option(ChannelOption.SoKeepalive, true)
            .Handler(new LoggingHandler("SRV-ICR"))
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                var pipeline = channel.Pipeline;
                pipeline.AddFirst("FrameDecoder", new LengthFieldBasedFrameDecoder(512, 2, 3, 2, 0));
                pipeline.AddLast("ReadTimeoutHandler", new ReadTimeoutHandler(20));
                pipeline.AddLast("WriteTimeoutHandler", new WriteTimeoutHandler(20));
                pipeline.AddLast("PacketProcessor", new PacketHandler());
                pipeline.AddLast("PacketEncoder", new PacketEncoder());
            }));

            var boundChannel = await ServerBootstrap.BindAsync(Resources.Configuration.ServerPort);

            var endpoint = (IPEndPoint)boundChannel.LocalAddress;

            Logger.Log(
                $"Listening on {endpoint.Address.MapToIPv4()}:{endpoint.Port}. Let's play ClashRoyale!",
                GetType());
        }
示例#17
0
        static async Task StartServer(int port)
        {
            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();
            var             bootstrap   = new ServerBootstrap();

            bootstrap.Group(bossGroup, workerGroup);
            bootstrap.Channel <TcpServerSocketChannel>();

            bootstrap
            .Option(ChannelOption.SoBacklog, 8192)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast(new HttpServerCodec());
                pipeline.AddLast(new HttpObjectAggregator(64 * 1024));
                pipeline.AddLast(new SampleRestfulHandler());
            }));

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

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

            await bootstrapChannel.CloseAsync();
        }
示例#18
0
        public GameSocketHost()
        {
            bossGroup   = new MultithreadEventLoopGroup(1);
            workerGroup = new MultithreadEventLoopGroup();
            bootstrap   = new ServerBootstrap();

            bootstrap.Group(bossGroup, workerGroup);
            bootstrap.Channel <TcpServerSocketChannel>();
            bootstrap
            .Option(ChannelOption.SoBacklog, GameEnvironment.SocketConfig.Backlog)
            .Handler(new LoggingHandler("SRV-LSTN"))
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                //pipeline.AddLast(new LoggingHandler("SRV-CONN"));
                //pipeline.AddLast("timeout", new IdleStateHandler(0, 0, 60));
                pipeline.AddLast("framing-enc", new LengthFieldPrepender(GameEnvironment.SocketConfig.ByteOrder,
                                                                         GameEnvironment.SocketConfig.PrePackageLength, 0, false));
                pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(GameEnvironment.SocketConfig.ByteOrder,
                                                                                 Int32.MaxValue, 0, GameEnvironment.SocketConfig.PrePackageLength, 0, GameEnvironment.SocketConfig.PrePackageLength, true));
                pipeline.AddLast("MainHandler", new MainHandler(this));
            }));

            //心跳超时
            SessionManager.HeartbeatTimeoutHandle += OnHeartTimeout;
        }
示例#19
0
        static async Task RunServerAsync()
        {
            IEventLoopGroup bossGroup;
            IEventLoopGroup workerGroup;

            bossGroup   = new MultithreadEventLoopGroup(1);
            workerGroup = new MultithreadEventLoopGroup();
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup);
                bootstrap.Channel <TcpServerSocketChannel>();
                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("stringDecoder", new PBDecoder());
                    //  pipeline.AddLast("stringEncoder", new PBEncoder());
                    pipeline.AddLast(new TestServerHandler());
                }));
                IChannel boundChannel = await bootstrap.BindAsync(8007);

                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)));
            }
        }
示例#20
0
        public static async Task RunServerAsync(int port)
        {
            var bossGroup   = new MultithreadEventLoopGroup();
            var workerGroup = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Option(ChannelOption.SoBacklog, 100)
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .ChildHandler(new ClientSessionInitializer());

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


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

                await bootstrapChannel.CloseAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Log.Error("RunServerAsync", ex);
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
示例#21
0
        static async Task RunHttpServerAsync(int port)
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            }

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

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap.Option(ChannelOption.SoBacklog, 8192);
                bootstrap.ChildHandler(new ActionChannelInitializer <DotNetty.Transport.Channels.IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    pipeline.AddLast(new HttpServerCodec());
                    pipeline.AddLast(new HttpObjectAggregator(65536 * 5));
                    pipeline.AddLast(new HttpDecoder());
                }));

                bootstrapChannel = await bootstrap.BindAsync(port);

                LOGGER.Info("start http server success. listener port:[{}]", port);
            }
            catch (Exception e)
            {
                throw new Exception("start http server ERROR! \n" + e.ToString());
            }
        }
示例#22
0
        void ReadPendingIsResetAfterEachRead0(ServerBootstrap sb, Bootstrap cb)
        {
            var serverInitializer = new MyInitializer();

            sb.Option(ChannelOption.SoBacklog, 1024);
            sb.ChildHandler(serverInitializer);

            // 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;

            cb.Handler(new MyInitializer());
            // 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);

            Task writeTask = this.clientChannel.WriteAndFlushAsync(Unpooled.WrappedBuffer(new byte[1024]));

            Assert.True(writeTask.Wait(DefaultTimeout), "Write task timed out");

            ExceptionHandler exceptionHandler = serverInitializer.ErrorHandler;

            Assert.True(exceptionHandler.Inactive.Wait(DefaultTimeout), "Handler inactive timed out");
            Assert.Equal(1, exceptionHandler.Count);
        }
示例#23
0
        public void Start()
        {
            _bossExecutor   = _nettyServerConfig.BossGroup;
            _workerExecutor = _nettyServerConfig.WorkerGroup;
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.Option(ChannelOption.TcpNodelay, true);
            serverBootstrap.Group(_bossExecutor, _workerExecutor);

            List <Task> tasks = new List <Task>();

            foreach (NettyServerTransport transport in _transports.Values)
            {
                var t = transport.StartAsync(serverBootstrap);
                tasks.Add(t);
            }
            try
            {
                Task.WaitAll(tasks.ToArray());
            }
            catch (AggregateException ex)
            {
                throw ex.GetBaseException();
            }
        }
示例#24
0
        public async Task Start(int port, Action <IChannel> initializer)
        {
            try
            {
                var serverBootstrap = new ServerBootstrap();
                serverBootstrap.Group(bossGroup, workerGroup);
#if LIBUV
                serverBootstrap.Channel <TcpServerChannel>();
#else
                serverBootstrap.Channel <TcpServerSocketChannel>();
#endif
                serverBootstrap
                .Option(ChannelOption.SoBacklog, 1024)
                .Handler(new LoggingHandler("SRV-LSTN"))
                .ChildHandler(new ActionChannelInitializer <IChannel>(initializer));

                boundChannel = await serverBootstrap.BindAsync(port);

                Log.Info($"Listen port : {port}");
            }
            catch (Exception e)
            {
                Log.Info(e, "Exception start server on port : " + port);
            }

            finally
            {
//                 await Task.WhenAll(
//                     bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
//                     workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))
//                 );
            }
        }
示例#25
0
        private static async Task TestAutoReadOffDuringReadOnlyReadsOneTime0(bool readOutsideEventLoopThread,
                                                                             ServerBootstrap sb, Bootstrap cb)
        {
            IChannel serverChannel = null;
            IChannel clientChannel = null;

            try
            {
                AutoReadInitializer serverInitializer = new AutoReadInitializer(!readOutsideEventLoopThread);
                AutoReadInitializer clientInitializer = new AutoReadInitializer(!readOutsideEventLoopThread);
                sb.Option(ChannelOption.SoBacklog, 1024)
                .Option(ChannelOption.AutoRead, true)
                .ChildOption(ChannelOption.AutoRead, true)
                // We want to ensure that we attempt multiple individual read operations per read loop so we can
                // test the auto read feature being turned off when data is first read.
                .ChildOption(ChannelOption.RcvbufAllocator, new TestRecvByteBufAllocator())
                .ChildHandler(serverInitializer);

                serverChannel = await sb.BindAsync();

                cb.Option(ChannelOption.AutoRead, true)
                // We want to ensure that we attempt multiple individual read operations per read loop so we can
                // test the auto read feature being turned off when data is first read.
                .Option(ChannelOption.RcvbufAllocator, new TestRecvByteBufAllocator())
                .Handler(clientInitializer);

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

                // 3 bytes means 3 independent reads for TestRecvByteBufAllocator
                clientChannel.WriteAndFlushAsync(Unpooled.WrappedBuffer(new byte[3])).Ignore();
                serverInitializer._autoReadHandler.AssertSingleRead();

                // 3 bytes means 3 independent reads for TestRecvByteBufAllocator
                serverInitializer._channel.WriteAndFlushAsync(Unpooled.WrappedBuffer(new byte[3])).Ignore();
                clientInitializer._autoReadHandler.AssertSingleRead();

                if (readOutsideEventLoopThread)
                {
                    serverInitializer._channel.Read();
                }
                serverInitializer._autoReadHandler.AssertSingleReadSecondTry();

                if (readOutsideEventLoopThread)
                {
                    clientChannel.Read();
                }
                clientInitializer._autoReadHandler.AssertSingleReadSecondTry();
            }
            finally
            {
                if (clientChannel != null)
                {
                    await clientChannel.CloseAsync();
                }
                if (serverChannel != null)
                {
                    await serverChannel.CloseAsync();
                }
            }
        }
示例#26
0
        private async Task StartAsync()
        {
            _bossGroup   = new MultithreadEventLoopGroup(1);
            _workerGroup = new MultithreadEventLoopGroup();

            var bootstrap = new ServerBootstrap();

            bootstrap.Group(_bossGroup, _workerGroup);

            bootstrap.Channel <TcpServerSocketChannel>();

            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 ServerHandler());
            }));

            _boundChannel = await bootstrap.BindAsync(ServerSettings.Port);
        }
示例#27
0
        public async Task ExecuteAsync()
        {
            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            var bootstrap = new ServerBootstrap();

            bootstrap.Group(bossGroup, workerGroup);

            bootstrap.Channel <TcpServerSocketChannel>();
            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 EchoServerHandler());
            }));

            IChannel boundChannel = await bootstrap.BindAsync(18007);

            Console.ReadLine();
            await boundChannel.CloseAsync();
        }
        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();
        }
示例#29
0
 protected override void Configure(ServerBootstrap sb, Bootstrap cb, IByteBufferAllocator allocator)
 {
     sb.LocalAddress(NewSocketAddress());
     sb.Option(ChannelOption.Allocator, allocator);
     sb.ChildOption(ChannelOption.Allocator, allocator);
     cb.Option(ChannelOption.Allocator, allocator);
 }
示例#30
0
        public async Task StartAsync(EndPoint endPoint)
        {
            var bootstrap   = new ServerBootstrap();
            var bossGroup   = new MultithreadEventLoopGroup();
            var workerGroup = new MultithreadEventLoopGroup();

            bootstrap.Channel <TcpServerSocketChannel>();
            bootstrap
            .Option(ChannelOption.SoBacklog, 128)
            .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
            .ChildOption(ChannelOption.SoKeepalive, true)
            .Group(bossGroup)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                var pipeline = channel.Pipeline;
                pipeline.AddLast(new HttpRequestDecoder());
                pipeline.AddLast(new HttpResponseEncoder());
                pipeline.AddLast(new HttpFlvHandler(_mediaStreamDic));
            }));
            try
            {
                _channel = await bootstrap.BindAsync(endPoint);

                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug($"HttpFlv服务主机启动成功,监听地址:{endPoint}。");
                }
            }
            catch
            {
                _logger.LogError($"HttpFlv服务主机启动失败,监听地址:{endPoint}。 ");
            }
        }