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)) // ); } }
public async Task StartAsync() { try { if (bossGroup == null && workerGroup == null) { if (_useLibuv) { var dispatcher = new DispatcherEventLoopGroup(); bossGroup = dispatcher; workerGroup = new WorkerEventLoopGroup(dispatcher); } else { bossGroup = new MultithreadEventLoopGroup(); workerGroup = new MultithreadEventLoopGroup(); } } if (bootstrap == null) { bootstrap = new ServerBootstrap(); bootstrap.Group(bossGroup, workerGroup); if (_useLibuv) { bootstrap.Channel <TcpServerChannel>(); } else { bootstrap.Channel <TcpServerSocketChannel>(); } bootstrap .Option(ChannelOption.SoBacklog, _soBacklog) .ChildHandler(new ActionChannelInitializer <IChannel>(ch => { IChannelPipeline pipeline = ch.Pipeline; _event.OnPipelineAction?.Invoke(pipeline); pipeline.AddLast(new TcpServerHandler(_event, connectionDict)); })); } if (_ipAddress == null) { _ipAddress = IPAddress.Any; } await Stop(); channel = await bootstrap.BindAsync(_ipAddress, _port); _event.OnStartAction?.Invoke(); } catch (Exception ex) { _event.OnStopAction?.Invoke(ex); } }
/// <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}。 "); } }
/// <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}。 "); } }
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; } }
static async Task RunServerAsync(int port, bool useLibuv) { if (useLibuv) { DispatcherEventLoopGroup dispatcher = new DispatcherEventLoopGroup(); bossGroup = dispatcher; workerGroup = new WorkerEventLoopGroup(dispatcher); } else { bossGroup = new MultithreadEventLoopGroup(1); workerGroup = new MultithreadEventLoopGroup(); //默认为CPU核数*2 } try { var bootstrap = new ServerBootstrap(); bootstrap.Group(bossGroup, workerGroup); if (useLibuv) { bootstrap.Channel <TcpServerChannel>(); } else { bootstrap.Channel <TcpServerSocketChannel>(); } bootstrap.Option(ChannelOption.SoBacklog, 65535) .Option(ChannelOption.RcvbufAllocator, new AdaptiveRecvByteBufAllocator()) .Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .ChildOption(ChannelOption.SoKeepalive, true) .ChildOption(ChannelOption.TcpNodelay, true) .ChildHandler(new ActionChannelInitializer <DotNetty.Transport.Channels.IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast("IdleChecker", new IdleStateHandler(50, 50, 0)); // 消息编码解码器 分发handler //每个channel channelpipeline 都会new一次,即每个客户端 pipeline.AddLast(new TcpServerEncoder(), new TcpServerDecoder(), new TcpServerHandler()); })); bootstrapChannel = await bootstrap.BindAsync(port); LOGGER.Info("start tcp server success. listener port:[{}]", port); } catch (Exception e) { LOGGER.Error(e, e.Message); throw new Exception("start tcp server ERROR! \n" + e.StackTrace); } }
/// <summary> /// 开启、关闭DotNetty服务 /// </summary> private async void RaiseStartServerHandler() { StartServerButtonEnabled = false; IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1); IEventLoopGroup workerGroup = new MultithreadEventLoopGroup(); try { var bootstrap = new ServerBootstrap(); bootstrap.Group(bossGroup, workerGroup); bootstrap.Channel <TcpServerSocketChannel>(); bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 4, 0, 4)); pipeline.AddLast(new MessagePackDecoder()); pipeline.AddLast(new LengthFieldPrepender(4)); pipeline.AddLast(new MessagePackEncoder()); pipeline.AddLast(DotNettyServerHandler); })); await bootstrap.BindAsync(ServerPort); } catch (Exception ex) { Console.WriteLine($"连接服务异常:{ex.Message}"); } }
public void RunServerAsync() { IEventLoopGroup eventLoop; eventLoop = new MultithreadEventLoopGroup(); try { // 服务器引导程序 var bootstrap = new ServerBootstrap(); bootstrap.Group(eventLoop); bootstrap.Channel <TcpServerSocketChannel>(); bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; //解码 pipeline.AddLast(new ServerDecoder()); //服务端为读IDLE pipeline.AddLast(new IdleStateHandler(60 * 5, 60 * 5, 60 * 5));//第一个参数为读,第二个为写,第三个为读写全部 //解码 pipeline.AddLast(new ServerEncoder()); //添加handler pipeline.AddLast(new NettyServer()); })); foreach (var server in _app.Value.Servers) { bootstrap.BindAsync(server.Port); LogHelper.Info("服务器启动:" + server.Name + "端口" + server.Port); } } catch (Exception ex) { Console.WriteLine(ex); } }
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()); } }
public async Task TestNotThrowBlockingOperationException() { IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1); IEventLoopGroup workerGroup = new MultithreadEventLoopGroup(1); IChannelGroup allChannels = new DefaultChannelGroup(); ServerBootstrap b = new ServerBootstrap(); b.Group(bossGroup, workerGroup); b.ChildHandler(new ChannelInboundHandlerAdapter0(allChannels)); b.Channel <TcpServerSocketChannel>(); var ch = await b.BindAsync(0); allChannels.Add(ch); await allChannels.CloseAsync(); await Task.WhenAll( bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)), workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)) ); await bossGroup.TerminationCompletion; await workerGroup.TerminationCompletion; }
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()); }
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(); }
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; }
public void TestAsyncResolutionFailure() { Bootstrap bootstrapA = new Bootstrap(); bootstrapA.Group(_groupA); bootstrapA.Channel <LocalChannel>(); bootstrapA.Resolver(new TestAddressResolverGroup(false)); bootstrapA.Handler(_dummyHandler); ServerBootstrap bootstrapB = new ServerBootstrap(); bootstrapB.Group(_groupB); bootstrapB.Channel <LocalServerChannel>(); bootstrapB.ChildHandler(_dummyHandler); var localAddress = bootstrapB.BindAsync(LocalAddress.Any).GetAwaiter().GetResult().LocalAddress; // Connect to the server using the asynchronous resolver. var connectFuture = bootstrapA.ConnectAsync(localAddress); // Should fail with the UnknownHostException. Assert.True(TaskUtil.WaitAsync(connectFuture, TimeSpan.FromSeconds(10)).GetAwaiter().GetResult()); Assert.False(connectFuture.IsSuccess()); Assert.IsType <System.Net.Sockets.SocketException>(connectFuture.Exception.InnerException); //Assert.False(connectFuture.Channel().isOpen()); }
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 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() { 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))); } }
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(); }
/// <summary> /// 开启、关闭DotNetty服务 /// </summary> private async void RaiseStartServerHandler() { StartServerButtonEnabled = false; IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1); IEventLoopGroup workerGroup = new MultithreadEventLoopGroup(); try { var bootstrap = new ServerBootstrap(); bootstrap.Group(bossGroup, workerGroup); bootstrap.Channel <TcpServerSocketChannel>(); bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel => { channel.Pipeline.AddLast(new ProtobufVarint32FrameDecoder()) .AddLast(new ProtobufDecoder(ChatInfo.Parser)) .AddLast(new ProtobufVarint32LengthFieldPrepender()) .AddLast(new ProtobufEncoder()) .AddLast(DotNettyServerHandler); })); await bootstrap.BindAsync(ServerPort); } catch (Exception ex) { Console.WriteLine($"连接服务异常:{ex.Message}"); } }
public async Task StartAsync(ServerBootstrap bootstrap) { bootstrap.Channel <TcpServerSocketChannel>(); bootstrap .Handler(new LoggingHandler($"{this._def.Name}", DotNetty.Handlers.Logging.LogLevel.INFO)) .ChildHandler(new ActionChannelInitializer <IChannel>(c => { this._pipelineSetup(c.Pipeline); })); IPAddress address = null; address = GetIPAddress(); // bootstrap.Option(nettyServerConfig.BootstrapOptions); _serverChannel = await bootstrap.BindAsync(address, this._requestedPort); var actualSocket = _serverChannel.LocalAddress; IPEndPoint localPoint = _serverChannel.LocalAddress as IPEndPoint; _actualPort = localPoint?.Port ?? 0; if (_actualPort == 0) { DnsEndPoint dnsPoint = _serverChannel.LocalAddress as DnsEndPoint; _actualPort = dnsPoint?.Port ?? 0; } //Preconditions.checkState(actualPort != 0 && (actualPort == requestedPort || requestedPort == 0)); _logger.LogInformation($"transport {_def.Name}:{_actualPort} was started."); }
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)); }
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); }
protected override Task StartAsync(CancellationToken cancellationToken) { try { var dispatcher = new DispatcherEventLoopGroup(); bossGroup = dispatcher; workerGroup = new WorkerEventLoopGroup(dispatcher); var bootstrap = new ServerBootstrap(); bootstrap.Group(bossGroup, workerGroup); bootstrap.Channel <TcpServerChannel>(); bootstrap //.Handler(new LoggingHandler("SRV-LSTN")) .ChildHandler(new ActionChannelInitializer <IChannel>(channel => { InitChannel(channel); })) .Option(ChannelOption.SoBacklog, 1048576); if (nettyOptions.Host == "") { boundChannel = bootstrap.BindAsync(nettyOptions.Port).Result; } else { boundChannel = bootstrap.BindAsync(nettyOptions.Host, nettyOptions.Port).Result; } } catch (Exception ex) { } return(Task.CompletedTask); }
static async Task RunServerAsync() { IEventLoopGroup eventLoop = new MultithreadEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.Group(eventLoop); bootstrap.Channel <TcpServerSocketChannel>(); bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(chl => { chl.Pipeline.AddLast(new ServerTestHandler()); })); IChannel channel = await bootstrap.BindAsync(3000); Console.WriteLine("服务器已启动........."); Console.ReadLine();//阻塞线程 await channel.CloseAsync(); } catch (Exception ex) { } finally { await eventLoop.ShutdownGracefullyAsync(); } }
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)); }
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); } }
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); }
public async Task Start() { bossGroup = new MultithreadEventLoopGroup(1); workerGroup = new MultithreadEventLoopGroup(); try { var bootstrap = new ServerBootstrap(); bootstrap.Group(bossGroup, workerGroup); bootstrap .Channel <TcpServerSocketChannel>() .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("encoder", new ModbusEncoder()); pipeline.AddLast("decoder", new ModbusDecoder(true)); pipeline.AddLast("request", new ModbusRequestHandler(responseService)); })); serverState = ServerState.Starting; Channel = await bootstrap.BindAsync(Port); serverState = ServerState.Started; } finally { } }
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)); }
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}。 "); } }