public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Starting DiscardServer"); _logger.LogInformation($"listening on port: {_appConfig.Value.Port}"); _bossGroup = new MultithreadEventLoopGroup(1); _workGroup = new MultithreadEventLoopGroup(); _bootstrap .Group(_bossGroup, _workGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .Handler(new LoggingHandler("LSTN")) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new LoggingHandler("CONN")); pipeline.AddLast(new DiscardServerHandler(_logger)); })); bootstrapChannel = _bootstrap.BindAsync(_appConfig.Value.Port); return(Task.CompletedTask); }
private static async Task RunServerAsync() { IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1); IEventLoopGroup workerGroup = new MultithreadEventLoopGroup(); EchoServerHandler serverHandler = new EchoServerHandler(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .Handler(new LoggingHandler("SRV-LSTN")) .ChildHandler(new ActionChannelInitializer <IChannel>(channel => { channel.Pipeline.AddLast(new LoggingHandler("SRV-CONN")) .AddLast(serverHandler); })); IChannel boundChannel = await bootstrap.BindAsync(Port); // Console.ReadLine(); // await boundChannel.CloseAsync(); await boundChannel.CloseCompletion; } finally { await Task.WhenAll(bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)), workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))); } }
public static async Task <Func <IObservable <IRequest>, IObservable <IResponse> > > Create( Action <IChannelPipeline> pipelineConfigurator, int port) { var handler = new SocketHandler(); var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup(); var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipelineConfigurator(pipeline); pipeline.AddLast("handler", handler); })); var boundChannel = await bootstrap.BindAsync(port); return((requests) => { requests .OfType <ITcpRequest>() .Subscribe(handler); return handler; }); }
private void InitializeUdpChannel() { if (_logger.IsInfo) { _logger.Info($"Starting Discovery UDP Channel: {_networkConfig.MasterHost}:{_networkConfig.MasterPort}"); } _group = new MultithreadEventLoopGroup(1); var bootstrap = new Bootstrap(); bootstrap .Group(_group); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { bootstrap .ChannelFactory(() => new SocketDatagramChannel(AddressFamily.InterNetwork)) .Handler(new ActionChannelInitializer <IDatagramChannel>(InitializeChannel)); } else { bootstrap .Channel <SocketDatagramChannel>() .Handler(new ActionChannelInitializer <IDatagramChannel>(InitializeChannel)); } _bindingTask = bootstrap.BindAsync(IPAddress.Parse(_networkConfig.MasterHost), _networkConfig.MasterPort) .ContinueWith(t => _channel = t.Result); }
/// <summary> /// 启动主机。 /// </summary> /// <param name="endPoint">主机终结点。</param> /// <returns>一个任务。</returns> public override async Task StartAsync(EndPoint endPoint) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.Debug($"准备启动服务主机,监听地址:{endPoint}。"); } var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup(); var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddLast(new LengthFieldPrepender(4)); pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4)); pipeline.AddLast(new ServerHandler(MessageListener, _logger, _serializer)); })); _channel = await bootstrap.BindAsync(endPoint); if (_logger.IsEnabled(LogLevel.Debug)) { _logger.Debug($"服务主机启动成功,监听地址:{endPoint}。"); } }
public void ServerCloseSocketInputProvidesData() { var clientGroup = new MultithreadEventLoopGroup(1); var serverGroup = new MultithreadEventLoopGroup(1); try { var serverCompletion = new TaskCompletionSource(); var serverHandler = new ServerHandler(); ServerBootstrap sb = new ServerBootstrap() .Group(serverGroup) .Channel <TcpServerSocketChannel>() .ChildHandler( new ActionChannelInitializer <ISocketChannel>( ch => { // Don't use the HttpServerCodec, because we don't want to have content-length or anything added. ch.Pipeline.AddLast(new HttpRequestDecoder(4096, 8192, 8192, true)); ch.Pipeline.AddLast(new HttpObjectAggregator(4096)); ch.Pipeline.AddLast(serverHandler); serverCompletion.TryComplete(); })); var clientHandler = new ClientHandler(); Bootstrap cb = new Bootstrap() .Group(clientGroup) .Channel <TcpSocketChannel>() .Handler( new ActionChannelInitializer <ISocketChannel>( ch => { ch.Pipeline.AddLast(new HttpClientCodec(4096, 8192, 8192, true)); ch.Pipeline.AddLast(new HttpObjectAggregator(4096)); ch.Pipeline.AddLast(clientHandler); })); Task <IChannel> task = sb.BindAsync(IPAddress.Loopback, IPEndPoint.MinPort); task.Wait(TimeSpan.FromSeconds(5)); Assert.True(task.Status == TaskStatus.RanToCompletion); IChannel serverChannel = task.Result; int port = ((IPEndPoint)serverChannel.LocalAddress).Port; task = cb.ConnectAsync(IPAddress.Loopback, port); task.Wait(TimeSpan.FromSeconds(5)); Assert.True(task.Status == TaskStatus.RanToCompletion); IChannel clientChannel = task.Result; serverCompletion.Task.Wait(TimeSpan.FromSeconds(5)); clientChannel.WriteAndFlushAsync(new DefaultHttpRequest(HttpVersion.Http11, HttpMethod.Get, "/")).Wait(TimeSpan.FromSeconds(1)); Assert.True(serverHandler.WaitForCompletion()); Assert.True(clientHandler.WaitForCompletion()); } finally { Task.WaitAll( clientGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)), serverGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5))); } }
public async void Start(string ip, int port) { try { _group = new MultithreadEventLoopGroup(); _bootstrap = new Bootstrap(); _bootstrap .Group(_group) .Channel <TcpSocketChannel>() .Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new MobusClientHandler()); })); _clientChannel = await _bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port)); } catch (Exception exp) { if (exp.InnerException != null) { logger.Error(exp.InnerException, "Mobus模拟客户端异常"); } else { logger.Error(exp, "Mobus模拟客户端异常"); } } }
public static async Task RunMasterClient(string targetHost, int port, string password, MasterClient clientType, ServerConfiguration WebApi, int connectedAccountLimit = 0, int clientPort = 0, byte serverGroup = 0, string serverHost = "") { var group = new MultithreadEventLoopGroup(); var bootstrap = new Bootstrap(); bootstrap .Group(group) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new LengthFieldPrepender(2)); pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); pipeline.AddLast(new StringEncoder(), new StringDecoder()); pipeline.AddLast(new MasterClientSession(password)); })); var connection = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(targetHost), port)); await connection.WriteAndFlushAsync(new Channel() { Password = password, ClientName = clientType.Name, ClientType = (byte)clientType.Type, ConnectedAccountsLimit = connectedAccountLimit, Port = clientPort, ServerGroup = serverGroup, Host = serverHost, WebApi = WebApi }); }
public async Task RunServerAsync() { var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup(); try { var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => _pipelineFactory(channel).CreatePipeline())); var bootstrapChannel = await bootstrap.BindAsync(_configuration.Value.Port).ConfigureAwait(false); Console.CancelKeyPress += ((s, a) => { ClosingEvent.Set(); }); ClosingEvent.WaitOne(); await bootstrapChannel.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { _logger.Error(ex.Message); } finally { await Task.WhenAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync()).ConfigureAwait(false); } }
static async Task RunClientAsync(string ip, int port) { var group = new MultithreadEventLoopGroup(); string targetHost = null; try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter())); pipeline.AddLast(new StringEncoder(), new StringDecoder(), handler); })); IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port)); for (;;) { Console.Write("$> "); var line = Console.ReadLine(); if (string.IsNullOrEmpty(line)) { continue; } try { var response = GameHandler.HandleClientCmd(handler.GetEventHandler(), line); if (response != null) { var serObj = SerializeHandler.SerializeObj(response); await bootstrapChannel.WriteAndFlushAsync(serObj + "\r\n"); } } catch (Exception e) { Console.Error.WriteLine(e.Message); } if (string.Equals(line, "bye", StringComparison.OrdinalIgnoreCase)) { await bootstrapChannel.CloseAsync(); break; } } await bootstrapChannel.CloseAsync(); } finally { group.ShutdownGracefullyAsync().Wait(1000); } }
static async Task RunClientAsync() { var group = new MultithreadEventLoopGroup(); try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter())); pipeline.AddLast(new StringEncoder(), new StringDecoder(), new ClientHandler()); })); IPAddress ip = IPAddress.Parse("127.0.0.1"); IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(ip, 4242)); for (; ;) { string line = Console.ReadLine(); if (string.IsNullOrEmpty(line)) { continue; } try { await bootstrapChannel.WriteAndFlushAsync(line + "\r\n"); } catch { Console.WriteLine("Deconnection..."); await bootstrapChannel.CloseAsync(); break; } if (string.Equals(line, "/leave", StringComparison.OrdinalIgnoreCase)) { await bootstrapChannel.CloseAsync(); break; } } await bootstrapChannel.CloseAsync(); } catch (Exception e) { Console.Error.WriteLine("Serveur introuvable"); } finally { group.ShutdownGracefullyAsync().Wait(1000); } }
public JT808TcpClient(DeviceConfig deviceConfig, IServiceProvider serviceProvider) { DeviceConfig = deviceConfig; LoggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); JT808ClientSendAtomicCounterService jT808SendAtomicCounterService = serviceProvider.GetRequiredService <JT808ClientSendAtomicCounterService>(); JT808ClientReceiveAtomicCounterService jT808ReceiveAtomicCounterService = serviceProvider.GetRequiredService <JT808ClientReceiveAtomicCounterService>(); IJT808Config jT808Config = serviceProvider.GetRequiredService <IJT808Config>(); group = new MultithreadEventLoopGroup(1); Bootstrap bootstrap = new Bootstrap(); bootstrap.Group(group); bootstrap.Channel <TcpSocketChannel>(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { bootstrap.Option(ChannelOption.SoReuseport, true); } bootstrap .Option(ChannelOption.SoBacklog, 8192) .Handler(new ActionChannelInitializer <IChannel>(channel => { 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("systemIdleState", new IdleStateHandler(60, deviceConfig.Heartbeat, 3600)); channel.Pipeline.AddLast("jt808TcpDecode", new JT808ClientTcpDecoder()); channel.Pipeline.AddLast("jt808TcpEncode", new JT808ClientTcpEncoder(jT808Config, jT808SendAtomicCounterService, LoggerFactory)); channel.Pipeline.AddLast("jt808TcpClientConnection", new JT808TcpClientConnectionHandler(this)); channel.Pipeline.AddLast("jt808TcpService", new JT808TcpClientHandler(jT808ReceiveAtomicCounterService, this)); })); clientChannel = bootstrap.ConnectAsync(IPAddress.Parse(DeviceConfig.TcpHost), DeviceConfig.TcpPort).Result; }
public async Task StartAsync(EndPoint endPoint) { _logger.LogInformation($"准备启动服务主机,监听地址:{endPoint}"); var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup(); var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddLast(new LengthFieldPrepender(_lengthFieldPrepender)); pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, _basedFrame, 0, _basedFrame)); pipeline.AddLast(new TransportMessageChannelHandlerDecodeAdapter(_transportMessageDecoder)); pipeline.AddLast(new TransportMessageChannelHandlerEncodeAdapter(async(contenxt, message) => { var sender = new DefaultDotNettyServerMessageSender(_transportMessageEncoder, contenxt); await OnReceived(sender, message); }, _logger)); })); _channel = await bootstrap.BindAsync(endPoint); _logger.LogInformation($"服务主机启动成功,监听地址:{endPoint}"); }
private static async Task RunClientAsync() { LoggingHelper.SetNLogLogger(); IEventLoopGroup group = new MultithreadEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.Group(group) .Channel <TcpSocketChannel>() .Handler(new WorldClockClientInitializer()); // Make a new connection. IChannel ch = await b.ConnectAsync(IPAddress.Parse(Host), Port); // Get the handler instance to initiate request. WorldClockClientHandler handler = ch.Pipeline.Get <WorldClockClientHandler>(); // Request and get the response. IList <string> response = handler.GetLocalTimes(TimeZoneIds); // Close the connection. await ch.CloseAsync(); // Print the response at last but not least. for (int i = 0; i < TimeZoneIds.Count; i++) { Console.WriteLine($"{TimeZoneIds[i]}: {response[i]}"); } } finally { await group.ShutdownGracefullyAsync(); } }
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 async Task StartAsync(EndPoint endPoint) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug($"准备启动服务主机,监听地址:{endPoint}。"); } var bossGroup = new MultithreadEventLoopGroup(); var workerGroup = new MultithreadEventLoopGroup(4); var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddLast(new LengthFieldPrepender(4)); pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4)); pipeline.AddLast(new TransportMessageChannelHandlerAdapter(_transportMessageDecoder)); pipeline.AddLast(new ServerHandler(async(contenxt, message) => { var sender = new DotNettyServerMessageSender(_transportMessageEncoder, contenxt); await OnReceived(sender, message); }, _logger)); })); _channel = await bootstrap.BindAsync(endPoint); if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug($"服务主机启动成功,监听地址:{endPoint}。"); } }
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 { } }
/// <summary> /// 构造函数 /// </summary> /// <param name="host"></param> /// <param name="port"></param> /// <param name="clusterToken"></param> /// <param name="logger"></param> public TCPServer(string host, int port, string clusterToken, ILog logger) : base(host, port, clusterToken, logger) { _host = host; _port = port; _logger = logger; MultithreadEventLoopGroup bossGroup = new MultithreadEventLoopGroup(); MultithreadEventLoopGroup workerGroup = new MultithreadEventLoopGroup(); _serverBootstrap = new ServerBootstrap() .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 1024) .ChildHandler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast("framing-enc", new LengthFieldPrepender(2)); //数据包最大长度 pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); ServerHandler serverHandler = new ServerHandler(_logger) { OnInvoke = Invoke }; pipeline.AddLast(serverHandler); })); }
public static async Task RunServerAsync(int port, EncoderFactory encryptor, DecoderFactory decryptor, IEnumerable <IPacketHandler> packetList, bool isWorldClient) { MultithreadEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1); MultithreadEventLoopGroup workerGroup = new MultithreadEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { SessionFactory.Instance.Sessions[channel.Id.AsLongText()] = 0; IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast((MessageToMessageDecoder <IByteBuffer>)decryptor.GetDecoder()); pipeline.AddLast(new ClientSession(channel, packetList, isWorldClient)); pipeline.AddLast((MessageToMessageEncoder <string>)encryptor.GetEncoder()); })); IChannel bootstrapChannel = await bootstrap.BindAsync(port); Console.ReadLine(); await bootstrapChannel.CloseAsync(); } catch (Exception ex) { Logger.Log.Error(ex.Message); } finally { Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync()); } }
public async Task TestBindMultiple() { DefaultChannelGroup channelGroup = new DefaultChannelGroup(); IEventLoopGroup group = new MultithreadEventLoopGroup(1); try { for (int i = 0; i < 100; i++) { Bootstrap udpBootstrap = new Bootstrap(); udpBootstrap .Group(group) .Channel <SocketDatagramChannel>() .Option(ChannelOption.SoBroadcast, true) .Handler(new ChannelInboundHandlerAdapter0()); var datagramChannel = await udpBootstrap .BindAsync(new IPEndPoint(IPAddress.Loopback, 0)); channelGroup.Add(datagramChannel); } Assert.Equal(100, channelGroup.Count); } finally { await channelGroup.CloseAsync(); await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }
public async Task StartAsync(Action <object> logger) { PlatformProvider.Platform = new UWPPlatform(); this.eventLoopGroup = new MultithreadEventLoopGroup(); string pfxDir = "dotnetty.com.pfx"; var cert = new X509Certificate2(pfxDir, "password"); string targetHost = cert.GetNameInfo(X509NameType.DnsName, false); var streamSocket = new StreamSocket(); await streamSocket.ConnectAsync(new HostName(ClientSettings.Host.ToString()), ClientSettings.Port.ToString(), SocketProtectionLevel.PlainSocket); streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); await streamSocket.UpgradeToSslAsync(SocketProtectionLevel.Tls12, new HostName(targetHost)); var streamSocketChannel = new StreamSocketChannel(streamSocket); streamSocketChannel.Pipeline.AddLast(new LoggingHandler()); streamSocketChannel.Pipeline.AddLast("framing-enc", new LengthFieldPrepender(2)); streamSocketChannel.Pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); streamSocketChannel.Pipeline.AddLast("echo", new EchoClientHandler(logger)); await this.eventLoopGroup.GetNext().RegisterAsync(streamSocketChannel); }
public void InitialDispatcherClient() { Task.Run(async() => { var group = new MultithreadEventLoopGroup(); var bootstrap = new Bootstrap(); bootstrap.Group(group) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new ClientConnectionHandler(bootstrap, channeldic, loggerFactory)); })); optionsMonitor.OnChange(options => { List <string> lastRemoteServers = new List <string>(); if (options.RemoteServers != null) { lastRemoteServers = options.RemoteServers; } DelRemoteServsers(lastRemoteServers); AddRemoteServsers(bootstrap, lastRemoteServers); }); await InitRemoteServsers(bootstrap); }); }
public async Task Run() { IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, _workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .ChildOption(ChannelOption.TcpNodelay, true) .ChildOption(ChannelOption.SoKeepalive, true) .ChildHandler( new ActionChannelInitializer <IChannel>( ChildChannelInit)); IChannel serverChannel = await bootstrap.BindAsync(EndPoint); ServerChannel = serverChannel; } catch { Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), _workerGroup.ShutdownGracefullyAsync()); throw; } }
public async Task TestUnhealthyChannelIsOfferedWhenNoHealthCheckRequested() { var group = new MultithreadEventLoopGroup(); var addr = new LocalAddress(LOCAL_ADDR_ID); Bootstrap cb = new Bootstrap().RemoteAddress(addr).Group(group).Channel <LocalChannel>(); ServerBootstrap sb = new ServerBootstrap() .Group(group) .Channel <LocalServerChannel>() .ChildHandler( new ActionChannelInitializer <LocalChannel>( ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter())) ); // Start server IChannel sc = await sb.BindAsync(addr); var handler = new CountingChannelPoolHandler(); var pool = new SimpleChannelPool(cb, handler, ChannelActiveHealthChecker.Instance, false); IChannel channel1 = await pool.AcquireAsync(); await channel1.CloseAsync(); await pool.ReleaseAsync(channel1); IChannel channel2 = await pool.AcquireAsync(); //verifying that in fact the channel2 is different that means is not pulled from the pool Assert.NotSame(channel1, channel2); await sc.CloseAsync(); await channel2.CloseAsync(); await group.ShutdownGracefullyAsync(); }
private async Task StartServer(int port) { InternalLoggerFactory.DefaultFactory.AddProvider(new NLogLoggerProvider()); Log.Info("Waiting 15s before starting the server"); await Task.Delay(15000); var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup(); var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Handler(new LoggingHandler(typeof(Server).FullName)) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new ProtobufVarint32FrameDecoder()); pipeline.AddLast(new ProtobufDecoder(Envelope.Parser)); pipeline.AddLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.AddLast(new ProtobufEncoder()); pipeline.AddLast(new ServerHandler()); })); _channel = await bootstrap.BindAsync(port); }
static async Task RunClientAsync() { var group = new MultithreadEventLoopGroup(); try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(new ActionChannelInitializer <ISocketChannel>(c => { IChannelPipeline pipeline = c.Pipeline; pipeline.AddLast(new HelloClientHandler()); })); IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3399)); Console.ReadLine(); await clientChannel.CloseAsync(); } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }
public static async Task RunMasterServerAsync(int port, string password) { var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup(); try { var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddLast("framing-enc", new LengthFieldPrepender(2)); pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); pipeline.AddLast(new StringEncoder(), new StringDecoder()); pipeline.AddLast(new MasterServerSession(password)); })); var bootstrapChannel = await bootstrap.BindAsync(port).ConfigureAwait(false); Logger.Log.Info( string.Format(LogLanguage.Instance.GetMessageFromKey(LanguageKey.MASTER_SERVER_LISTENING))); Console.ReadLine(); await bootstrapChannel.CloseAsync().ConfigureAwait(false); } finally { Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync()); } }
public ServerBootstrap(ServerOptions serverOptions, ClientOptions clientOptions, IServiceProvider serviceProvider) { _serverOptions = serverOptions; _clientOptions = clientOptions; _serviceProvider = serviceProvider; BossGroup = new MultithreadEventLoopGroup(_serverOptions.BossEventLoopCount); WorkerGroup = new MultithreadEventLoopGroup(_serverOptions.WorkerEventLoopCount); Bootstrap = new DotNetty.Transport.Bootstrapping.ServerBootstrap(); Bootstrap .Group(BossGroup, WorkerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 10240) .Option(ChannelOption.SoReuseaddr, true) // .Handler(new LoggingHandler("SRV-LSTN")) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; //pipeline.AddLast(new LoggingHandler("SRV-CONN")); pipeline.AddLast("framing-dec1", new LengthFieldBasedFrameDecoder(int.MaxValue, 4, 4, -8, 0)); pipeline.AddLast("framing-dec2", new MessageDecoder()); pipeline.AddLast("framing-enc1", new MessageEncoder()); pipeline.AddLast("IdleState", new IdleStateHandler(0, 0, _clientOptions.HeartseatInterval + 10)); pipeline.AddLast("Heartbeat1", new HeartbeatServerHandler()); //new HeartbeatServerHandler() pipeline.AddLast("echo2", _serviceProvider.GetService <DispatchServerHandler>()); })); GlobalContext.Current.Server(this); }
public JT809SubordinateClient( IServiceProvider provider, ILoggerFactory loggerFactory, IJT809SubordinateLinkNotifyService subordinateLinkNotifyService, IJT809VerifyCodeGenerator verifyCodeGenerator, JT809Serializer serializer) { this.serviceProvider = provider; this.verifyCodeGenerator = verifyCodeGenerator; this.serializer = serializer; this.logger = loggerFactory.CreateLogger <JT809SubordinateClient>(); this.subordinateLinkNotifyService = subordinateLinkNotifyService; group = new MultithreadEventLoopGroup(); bootstrap = new Bootstrap(); bootstrap.Group(group) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; //下级平台1分钟发送心跳 //上级平台是3分钟没有发送就断开连接 using var scope = serviceProvider.CreateScope(); pipeline.AddLast("jt809SubClientBuffer", new DelimiterBasedFrameDecoder(int.MaxValue, Unpooled.CopiedBuffer(new byte[] { JT809Package.BEGINFLAG }), Unpooled.CopiedBuffer(new byte[] { JT809Package.ENDFLAG }))); pipeline.AddLast("jt809SubClientSystemIdleState", new IdleStateHandler(180, 60, 200)); pipeline.AddLast("jt809SubClientEncode", scope.ServiceProvider.GetRequiredService <JT809Encoder>()); pipeline.AddLast("jt809SubClientDecode", scope.ServiceProvider.GetRequiredService <JT809Decoder>()); pipeline.AddLast("jt809SubClientConnection", scope.ServiceProvider.GetRequiredService <JT809SubordinateClientConnectionHandler>()); pipeline.AddLast("jt809SubClientServer", scope.ServiceProvider.GetRequiredService <JT809SubordinateClientHandler>()); })); }
/// <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}"); } }