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}。 "); } }
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 static RemoteConnection CreateConnection(Role role, INode socketAddress, int poolSize, IHeliosConnectionHandler upstreamHandler) { if (role == Role.Client) { var connection = new ClientBootstrap().SetTransport(TransportType.Tcp) .SetOption("TcpNoDelay", true) .SetEncoder(Encoders.DefaultEncoder) //LengthFieldPrepender .SetDecoder(Encoders.DefaultDecoder) //LengthFieldFrameBasedDecoder .WorkerThreads(poolSize).Build().NewConnection(socketAddress); var remoteConnection = new RemoteConnection(connection, upstreamHandler); remoteConnection.Open(); return(remoteConnection); } else //server { var connection = new ServerBootstrap().SetTransport(TransportType.Tcp) .SetOption("TcpNoDelay", true) .SetEncoder(Encoders.DefaultEncoder) //LengthFieldPrepender .SetDecoder(Encoders.DefaultDecoder) //LengthFieldFrameBasedDecoder .WorkerThreads(poolSize).Build().NewConnection(socketAddress); var remoteConnection = new RemoteConnection(connection, upstreamHandler); remoteConnection.Open(); return(remoteConnection); } }
void BufRelease0(ServerBootstrap sb, Bootstrap cb) { var serverHandler = new BufWriterHandler(); var clientHandler = new BufWriterHandler(); sb.ChildHandler(serverHandler); cb.Handler(clientHandler); // start server Task <IChannel> task = sb.BindAsync(LoopbackAnyPort); Assert.True(task.Wait(DefaultTimeout), "Server bind timed out"); this.serverChannel = task.Result; Assert.NotNull(this.serverChannel.LocalAddress); var endPoint = (IPEndPoint)this.serverChannel.LocalAddress; // connect to server task = cb.ConnectAsync(endPoint); Assert.True(task.Wait(DefaultTimeout), "Connect to server timed out"); this.clientChannel = task.Result; Assert.NotNull(this.clientChannel.LocalAddress); // Ensure the server socket accepted the client connection *and* initialized pipeline successfully. Assert.True(serverHandler.Added.Wait(DefaultTimeout), "Channel HandlerAdded timed out"); // and then close all sockets. this.serverChannel.CloseAsync().Wait(DefaultTimeout); this.clientChannel.CloseAsync().Wait(DefaultTimeout); serverHandler.Check(); clientHandler.Check(); serverHandler.Release(); clientHandler.Release(); }
/// <summary> /// 启动tcp服务 /// </summary> /// <returns></returns> public async Task <IPEndPoint> OpenServer() { var dispatcher = new DispatcherEventLoopGroup(); _bossGroup = dispatcher; _workerGroup = new WorkerEventLoopGroup(dispatcher); _bootstrap = new ServerBootstrap() .Channel <TcpServerChannel>() .Group(_bossGroup, _workerGroup) .Option(ChannelOption.SoBacklog, 100) .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .ChildOption(ChannelOption.ConnectTimeout, new TimeSpan(0, 0, 5)) .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 MessageDecoder <RpcGlobalMessageBase <object> >(_serialize)); pipeline.AddLast(new MessageEncoder <object>(_serialize)); pipeline.AddLast(new RpcServerHandler(_logger, _localProxyGenerator)); })); var port = OxygenSetting.ServerPort ?? GlobalCommon.GetFreePort(); boundChannel = await _bootstrap.BindAsync(port); _logger.LogInfo($"bind tcp 0.0.0.0:{port} to listen"); return(new IPEndPoint(GlobalCommon.GetMachineIp(), port)); }
public void SetUp() { if (!HighPerformance) { ClientSendBuffer = new ConcurrentCircularBuffer <NetworkData>(BufferSize); ClientReceiveBuffer = new ConcurrentCircularBuffer <NetworkData>(BufferSize); ServerReceiveBuffer = new ConcurrentCircularBuffer <NetworkData>(BufferSize); } ClientReceived = new AtomicCounter(0); ServerReceived = new AtomicCounter(0); _clientExecutor = new AssertExecutor(); _serverExecutor = new AssertExecutor(); var serverBootstrap = new ServerBootstrap() .WorkerThreads(2) .Executor(_serverExecutor) .SetTransport(TransportType) .SetEncoder(Encoder) .SetDecoder(Decoder) .SetAllocator(Allocator) .SetConfig(Config) .Build(); _server = serverBootstrap.NewConnection(Node.Loopback()); _clientConnectionFactory = new ClientBootstrap() .Executor(_clientExecutor) .SetTransport(TransportType) .SetEncoder(Encoder) .SetDecoder(Decoder) .SetAllocator(Allocator) .SetConfig(Config) .Build(); }
public async Task TestCloseAsync() { var addr = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId()); 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 pool = new FixedChannelPool(cb, new TestChannelPoolHandler(), 2); await pool.AcquireAsync(); await pool.AcquireAsync(); var closePromise = sc.NewPromise(); await pool.CloseAsync(); Assert.Equal(0, pool.AcquiredChannelCount); await sc.CloseAsync(closePromise); Assert.True(closePromise.IsSuccess); }
public override async Task Start(ServiceAddress serviceAddress) { _logger.LogDebug($"准备启动服务主机,监听地址:{serviceAddress}。"); var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup();//Default eventLoopCount is Environment.ProcessorCount * 2 var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .ChildOption(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 MicroMessageHandler(_codecFactory.GetDecoder())); pipeline.AddLast(new ServerHandler(_logger, async(contenxt, message) => { var sender = new DotNettyServerSender(_codecFactory.GetEncoder(), contenxt); await OnReceived(sender, message); })); })); var endPoint = serviceAddress.ToEndPoint(); _channel = await bootstrap.BindAsync(endPoint); _logger.LogInformation($"服务主机启动成功,监听地址:{serviceAddress}。"); }
public async Task TestReleaseAfterClosePool() { var addr = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId()); 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 pool = new FixedChannelPool(cb, new TestChannelPoolHandler(), 2); IChannel channel = await pool.AcquireAsync(); pool.Close(); await _group.GetNext().SubmitAsync(() => TaskUtil.Completed); var e = await Assert.ThrowsAsync <InvalidOperationException>(async() => await pool.ReleaseAsync(channel)); Assert.Same(FixedChannelPool.PoolClosedOnReleaseException, e); // Since the pool is closed, the Channel should have been closed as well. await channel.CloseCompletion; Assert.False(channel.Open, "Unexpected open channel"); await sc.CloseAsync(); pool.Close(); }
public async Task TestReleaseClosed() { var addr = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId()); 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 pool = new FixedChannelPool(cb, new TestChannelPoolHandler(), 2); IChannel channel = await pool.AcquireAsync(); await channel.CloseAsync(); await pool.ReleaseAsync(channel); await sc.CloseAsync(); pool.Close(); }
public async Task TestAcquireNewConnectionWhen() { var addr = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId()); 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 TestChannelPoolHandler(); var pool = new FixedChannelPool(cb, handler, 1); IChannel channel1 = await pool.AcquireAsync(); await channel1.CloseAsync(); #pragma warning disable CS4014 // 由于此调用不会等待,因此在调用完成前将继续执行当前方法 pool.ReleaseAsync(channel1); #pragma warning restore CS4014 // 由于此调用不会等待,因此在调用完成前将继续执行当前方法 IChannel channel2 = await pool.AcquireAsync(); Assert.NotSame(channel1, channel2); await sc.CloseAsync(); await channel2.CloseAsync(); pool.Close(); }
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))); } }
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); _logger.Information(LogLanguage.Instance.GetMessageFromKey(LanguageKey.MASTER_SERVER_LISTENING)); Console.ReadLine(); await bootstrapChannel.CloseAsync(); } finally { Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync()); } }
public proxyNettyServer(string cid, string mapHttpPort, string _ServiceUrl, string mapHttpsPort = null, int failtime = 100, int _maxPerfData = 100) : base(cid, failtime, _maxPerfData) { this.port = mapHttpPort; //http转发服务的端口,不是集群服务api的端口 this.httpsPort = mapHttpsPort; //同上 mapPortGroup_dic = new Dictionary <string, mapPortGroup>(StringComparer.OrdinalIgnoreCase); maphttpGroup_dic = new Dictionary <string, mapPortGroup>(StringComparer.OrdinalIgnoreCase); checkGroup = new MultithreadEventLoopGroup(); httpClient = new HttpHelper(new TimeSpan(0, 0, 3)); if (!string.IsNullOrEmpty(cid)) //如果cid==null,非本地服务,不需要启动dotnett服务 { bossGroup = new MultithreadEventLoopGroup(1); workerGroup = new MultithreadEventLoopGroup(); SERVER_HANDLER = new ProxyServerHandler(); portbootstrap = new ServerBootstrap(); httpbossGroup = new MultithreadEventLoopGroup(1); httpworkerGroup = new MultithreadEventLoopGroup(); httpbootstrap = new ServerBootstrap(); } this.serviceUrl = _ServiceUrl; this.id = (cid + this.serviceUrl).ToMD5(); //保证在同一个zone中,同一个服务url肯定的是同样的id; this.needReportChange = true; }
private async Task TestAcquireTimeout0(long timeoutMillis) { var addr = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId()); 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 TestChannelPoolHandler(); var pool = new FixedChannelPool(cb, handler, ChannelActiveHealthChecker.Instance, FixedChannelPool.AcquireTimeoutAction.Fail, TimeSpan.FromMilliseconds(timeoutMillis), 1, int.MaxValue); IChannel channel = await pool.AcquireAsync(); try { await Assert.ThrowsAsync <TimeoutException>(async() => await pool.AcquireAsync()); } finally { await sc.CloseAsync(); await channel.CloseAsync(); pool.Close(); } }
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.Port); Console.ReadLine(); await bootstrapChannel.CloseAsync(); } catch (Exception ex) { Logger.Log.Error(ex.Message); } finally { Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync()); } }
public void Connect() { ServerBootstrap sb = new ServerBootstrap() .Group(this.group) .Channel <TcpServerChannel>() .ChildHandler(new ActionChannelInitializer <TcpChannel>(channel => { channel.Pipeline.AddLast("server logger", new LoggingHandler($"{nameof(ConnectTests)}")); })); Bootstrap cb = new Bootstrap() .Group(this.group) .Channel <TcpChannel>() .Handler(new ActionChannelInitializer <TcpChannel>(channel => { channel.Pipeline.AddLast("client logger", new LoggingHandler($"{nameof(ConnectTests)}")); })); // start server Task <IChannel> task = sb.BindAsync(LoopbackAnyPort); Assert.True(task.Wait(DefaultTimeout), "Server bind timed out"); this.serverChannel = task.Result; Assert.NotNull(this.serverChannel.LocalAddress); var endPoint = (IPEndPoint)this.serverChannel.LocalAddress; // connect to server task = cb.ConnectAsync(endPoint); Assert.True(task.Wait(DefaultTimeout), "Connect to server timed out"); this.clientChannel = task.Result; Assert.NotNull(this.clientChannel.LocalAddress); }
public NettyServer( int listenPort, Action<string, string, string, byte[]> dataReceivedAction, Action<string, string> clientConnectedAction) { this.listenPort = listenPort; this.channels = new Dictionary<string, IChannel>(); this.bossGroup = new MultithreadEventLoopGroup(1); this.workerGroup = new MultithreadEventLoopGroup(); this.bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel<TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .Handler(new LoggingHandler("SRV-LSTN")) .ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; //TODO: Receive InstanceId in the pipeline instead of part of the data buffer pipeline.AddLast("framing-enc", new LengthFieldPrepender(2)); pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(32 * 1024, 0, 2, 0, 2)); pipeline.AddLast("main", new NettyServerHandler(this, dataReceivedAction, clientConnectedAction)); })); }
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 async Task RunAsync(X509Certificate2 certificate, int threadCount, CancellationToken cancellationToken) { Contract.Requires(certificate != null); Contract.Requires(threadCount > 0); try { BootstrapperEventSource.Log.Info("Starting", null); PerformanceCounters.ConnectionsEstablishedTotal.RawValue = 0; PerformanceCounters.ConnectionsCurrent.RawValue = 0; this.tlsCertificate = certificate; this.parentEventLoopGroup = new MultithreadEventLoopGroup(1); this.eventLoopGroup = new MultithreadEventLoopGroup(threadCount); this.bufferAllocator = new PooledByteBufferAllocator(16 * 1024, 300 * 1024 * 1024 / threadCount); // reserve up to 300 MB of 16 KB buffers ServerBootstrap bootstrap = this.SetupBootstrap(); BootstrapperEventSource.Log.Info(string.Format("Initializing TLS endpoint on port {0} with certificate {1}.", MqttsPort, this.tlsCertificate.Thumbprint), null); this.serverChannel = await bootstrap.BindAsync(IPAddress.Any, MqttsPort); cancellationToken.Register(this.CloseAsync); BootstrapperEventSource.Log.Info("Started", null); } catch (Exception ex) { BootstrapperEventSource.Log.Error("Failed to start", ex); this.CloseAsync(); } }
public async Task StartAsync(EndPoint endPoint) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug($"准备启动服务主机,监听地址:{endPoint}。"); } var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup();//Default eventLoopCount is Environment.ProcessorCount * 2 var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .ChildOption(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 Task RunAsync(X509Certificate2 certificate, int threadCount, CancellationToken cancellationToken) { Contract.Requires(certificate != null); Contract.Requires(threadCount > 0); try { BootstrapperEventSource.Log.Info("Starting", null); PerformanceCounters.ConnectionsEstablishedTotal.RawValue = 0; PerformanceCounters.ConnectionsCurrent.RawValue = 0; PerformanceCounters.TotalCommandsReceived.RawValue = 0; PerformanceCounters.TotalMethodsInvoked.RawValue = 0; this.tlsCertificate = certificate; this.parentEventLoopGroup = new MultithreadEventLoopGroup(1); this.eventLoopGroup = new MultithreadEventLoopGroup(threadCount); ServerBootstrap bootstrap = this.SetupBootstrap(); BootstrapperEventSource.Log.Info($"Initializing TLS endpoint on port {MqttsPort.ToString()} with certificate {this.tlsCertificate.Thumbprint}.", null); this.serverChannel = await bootstrap.BindAsync(IPAddress.Any, MqttsPort); this.serverChannel.CloseCompletion.LinkOutcome(this.closeCompletionSource); cancellationToken.Register(this.CloseAsync); BootstrapperEventSource.Log.Info("Started", null); } catch (Exception ex) { BootstrapperEventSource.Log.Error("Failed to start", ex); this.CloseAsync(); } }
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 async void StartAsync(X509Certificate2 certificate, int threadCount, CancellationToken cancelToken) { Contract.Requires(certificate != null); Contract.Requires(threadCount > 0); try { parentEventLoopGroup = new MultithreadEventLoopGroup(1); eventLoopGroup = new MultithreadEventLoopGroup(threadCount); closeCompletionSource = new TaskCompletionSource(); ServerBootstrap svrBootstrap = new ServerBootstrap() .Group(parentEventLoopGroup, eventLoopGroup) .Option(ChannelOption.SoBacklog, 200) .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .ChildOption(ChannelOption.AutoRead, true) .Channel <TcpServerSocketChannel>() .Handler(new LoggingHandler("SRV_LSTN")) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { channel.Pipeline.AddLast(TlsHandler.Server(certificate)); channel.Pipeline.AddLast("echo", new EchoServerHandler()); })); theChannel = await svrBootstrap.BindAsync(IPAddress.Any, 3382); cancelToken.Register(closeAsync); } catch (Exception e) { Console.WriteLine(e.Message); } }
static void Main(string[] args) { var host = IPAddress.Any; var port = 9991; Console.Title = "Server"; Console.WriteLine("Starting server on {0}:{1}", host, port); var executor = new TryCatchExecutor(exception => Console.WriteLine("Unhandled exception: {0}", exception)); var bootstrapper = new ServerBootstrap() .WorkerThreads(2) .Executor(executor) .SetTransport(TransportType.Tcp) .Build(); var server = bootstrapper.NewReactor(NodeBuilder.BuildNode().Host(host).WithPort(port)); server.OnConnection += (address, connection) => { Console.WriteLine("Connected: {0}", address); connection.BeginReceive(Receive); }; server.OnDisconnection += (reason, address) => Console.WriteLine("Disconnected: {0}; Reason: {1}", address.RemoteHost, reason.Type); server.Start(); Console.WriteLine("Running, press any key to exit"); Console.ReadKey(); Console.WriteLine("Shutting down..."); server.Stop(); Console.WriteLine("Terminated"); }
static async Task Main(string[] args) { IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1); IEventLoopGroup workGroup = new MultithreadEventLoopGroup(); try { var bootstrap = new ServerBootstrap(); bootstrap.Group(bossGroup, workGroup); bootstrap.Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 8191) .ChildHandler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new HttpServerCodec()); pipeline.AddLast(new HttpObjectAggregator(65536)); })); IChannel bootstrapChannel = await bootstrap.BindAsync(IPAddress.IPv6Any, 8881); await bootstrapChannel.CloseAsync(); } catch (Exception) { throw; } finally { bossGroup.ShutdownGracefullyAsync().Wait(); } }
static async Task RunServerAsync() { Console.WriteLine("Gateway Start, ThreadName=" + System.Threading.Thread.CurrentThread.ManagedThreadId); var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup(); try { var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel<TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .Handler(new LoggingHandler(LogLevel.INFO)) .ChildHandler(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 GatewayHandler()); })); IChannel bootstrapChannel = await bootstrap.BindAsync(GatewaySettings.Port); Console.ReadLine(); await bootstrapChannel.CloseAsync(); } finally { Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync()); } }
public async Task StartAsync(EndPoint endPoint) { if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug($"准备启动服务主机,监听地址:{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 TransportMessageChannelHandlerAdapter(_transportMessageDecoder)); pipeline.AddLast(new ServerHandler((contenxt, message) => { var sender = new DotNettyServerMessageSender(_transportMessageEncoder, contenxt); OnReceived(sender, message); }, _logger)); })); _channel = await bootstrap.BindAsync(endPoint); if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug($"服务主机启动成功,监听地址:{endPoint}。"); }
public async Task Init() { if (_isInitialized) { throw new InvalidOperationException($"{nameof(PeerManager)} already initialized."); } _isInitialized = true; try { _bossGroup = new MultithreadEventLoopGroup(); _workerGroup = new MultithreadEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap .Group(_bossGroup, _workerGroup) .Channel <TcpServerSocketChannel>() .ChildOption(ChannelOption.SoBacklog, 100) .Handler(new LoggingHandler("BOSS", DotNetty.Handlers.Logging.LogLevel.TRACE)) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(ch => { Session session = new Session(LocalPort, _logManager, ch); session.RemoteHost = ((IPEndPoint)ch.RemoteAddress).Address.ToString(); session.RemotePort = ((IPEndPoint)ch.RemoteAddress).Port; InitializeChannel(ch, session); })); _bootstrapChannel = await bootstrap.BindAsync(LocalPort).ContinueWith(t => { if (t.IsFaulted) { AggregateException aggregateException = t.Exception; if (aggregateException?.InnerException is SocketException socketException && socketException.ErrorCode == 10048) { if (_logger.IsError) { _logger.Error($"Port {LocalPort} is in use. You can change the port used by adding: --{nameof(NetworkConfig).Replace("Config", "")}.{nameof(NetworkConfig.P2PPort)} 30303"); } } else { if (_logger.IsError) { _logger.Error($"{nameof(Init)} failed", t.Exception); } } return(null); } return(t.Result); }); if (_bootstrapChannel == null) { throw new NetworkingException($"Failed to initialize {nameof(_bootstrapChannel)}", NetworkExceptionType.Other); } }
public async void Start() { bossGroup = new MultithreadEventLoopGroup(1); workerGroup = new MultithreadEventLoopGroup(); try { var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .Handler(new LoggingHandler(LogLevel.INFO)) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new DelimiterBasedFrameDecoder(133680, Delimiters.LineDelimiter())); pipeline.AddLast(STRING_ENCODER, STRING_DECODER, new UpdaterServerHandler()); })); bootstrapChannel = await bootstrap.BindAsync(9527); Console.WriteLine("服务已启动..."); LoggerHelper.Info("服务已启动..."); } catch (Exception ex) { Console.WriteLine("服务启动异常:{0}", ex.StackTrace); LoggerHelper.Error("服务启动异常", ex); } }
public NettyServer( ILogger logger, int listenPort, Action <string, string, string, byte[]> dataReceivedAction, Action <string, string, System.Net.EndPoint> clientConnectedAction) { this.log = logger; this.listenPort = listenPort; this.channels = new Dictionary <string, IChannel>(); this.bossGroup = new MultithreadEventLoopGroup(1); this.workerGroup = new MultithreadEventLoopGroup(); this.bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .Handler(new LoggingHandler("SRV-LSTN")) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; //TODO: Receive InstanceId in the pipeline instead of part of the data buffer pipeline.AddLast("framing-enc", new LengthFieldPrepender(2)); pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(32 * 1024, 0, 2, 0, 2)); pipeline.AddLast("main", new NettyServerHandler(this.log, this, dataReceivedAction, clientConnectedAction)); })); }
public void TcpSocketChannel_can_connect_to_TcpServerSocketChannel() { IEventLoopGroup group1 = new MultithreadEventLoopGroup(2); IEventLoopGroup group2 = new MultithreadEventLoopGroup(2); var cb = new ClientBootstrap(); var sb = new ServerBootstrap(); var reads = 100; var resetEvent = new ManualResetEventSlim(); cb.Group(group1) .Channel <TcpSocketChannel>() .Handler( new ActionChannelInitializer <TcpSocketChannel>( channel => { channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4)) .AddLast(new LengthFieldPrepender(4, false)) .AddLast(new IntCodec()) .AddLast(new TestHandler()); })); sb.Group(group2) .Channel <TcpServerSocketChannel>() .ChildHandler( new ActionChannelInitializer <TcpSocketChannel>( channel => { channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4)) .AddLast(new LengthFieldPrepender(4, false)) .AddLast(new IntCodec()) .AddLast(new ReadCountAwaiter(resetEvent, reads)) .AddLast(new TestHandler()); })); IChannel sc = null; IChannel cc = null; try { // Start server sc = sb.BindAsync(TEST_ADDRESS).Result; // Connect to the server cc = cb.ConnectAsync(sc.LocalAddress).Result; foreach (var read in Enumerable.Range(0, reads)) { cc.WriteAndFlushAsync(read); } Assert.True(resetEvent.Wait(15000)); } finally { CloseChannel(cc); CloseChannel(sc); Task.WaitAll(group1.ShutdownGracefullyAsync(), group2.ShutdownGracefullyAsync()); } }
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 void TcpSocketChannel_can_connect_to_TcpServerSocketChannel() { IEventLoopGroup group1 = new MultithreadEventLoopGroup(2); IEventLoopGroup group2 = new MultithreadEventLoopGroup(2); var cb = new ClientBootstrap(); var sb = new ServerBootstrap(); var reads = 100; var resetEvent = new ManualResetEventSlim(); cb.Group(group1) .Channel<TcpSocketChannel>() .Handler( new ActionChannelInitializer<TcpSocketChannel>( channel => { channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4)) .AddLast(new LengthFieldPrepender(4, false)) .AddLast(new IntCodec()) .AddLast(new TestHandler()); })); sb.Group(group2) .Channel<TcpServerSocketChannel>() .ChildHandler( new ActionChannelInitializer<TcpSocketChannel>( channel => { channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4)) .AddLast(new LengthFieldPrepender(4, false)) .AddLast(new IntCodec()) .AddLast(new ReadCountAwaiter(resetEvent, reads)) .AddLast(new TestHandler()); })); IChannel sc = null; IChannel cc = null; try { // Start server sc = sb.BindAsync(TEST_ADDRESS).Result; // Connect to the server cc = cb.ConnectAsync(sc.LocalAddress).Result; foreach (var read in Enumerable.Range(0, reads)) { cc.WriteAndFlushAsync(read); } Assert.True(resetEvent.Wait(15000)); } finally { CloseChannel(cc); CloseChannel(sc); Task.WaitAll(group1.ShutdownGracefullyAsync(), group2.ShutdownGracefullyAsync()); } }
public void ServerBootrap_must_support_BindAsync_on_DnsEndpoints_for_SocketChannels() { var sb = new ServerBootstrap() .Channel<TcpServerSocketChannel>() .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { })) .Group(_serverGroup); var c = sb.BindAsync(new DnsEndPoint("localhost", 0)).Result; }
public void LocalChannel_batch_read_should_not_NRE() { var cb = new ClientBootstrap(); var sb = new ServerBootstrap(); var reads = 100; var resetEvent = new ManualResetEventSlim(); cb.Group(_group1) .Channel<LocalChannel>() .Handler( new ActionChannelInitializer<LocalChannel>( channel => { channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4)) .AddLast(new LengthFieldPrepender(4, false)) .AddLast(new TestHandler()); })); sb.Group(_group2) .Channel<LocalServerChannel>() .ChildHandler( new ActionChannelInitializer<LocalChannel>( channel => { channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4)) .AddLast(new LengthFieldPrepender(4, false)) .AddLast(new ReadCountAwaiter(resetEvent, reads)) .AddLast(new TestHandler()); })); IChannel sc = null; IChannel cc = null; try { // Start server sc = sb.BindAsync(TEST_ADDRESS).Result; // Connect to the server cc = cb.ConnectAsync(sc.LocalAddress).Result; foreach (var read in Enumerable.Range(0, reads)) { cc.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(read)); } Assert.True(resetEvent.Wait(5000)); } finally { CloseChannel(sc); CloseChannel(cc); } }
public async Task TcpSocketChannel_should_not_throw_on_shutdown() { AtomicReference<Exception> clientError = new AtomicReference<Exception>(null); AtomicReference<Exception> serverError = new AtomicReference<Exception>(null); IChannel s = null; IChannel c = null; try { var sb = new ServerBootstrap() .Channel<TcpServerSocketChannel>() .ChildHandler( new ActionChannelInitializer<TcpSocketChannel>( channel => { channel.Pipeline.AddLast(new FailAssertionHandler(serverError)); })) .Group(_serverGroup); s = sb.BindAsync(new IPEndPoint(IPAddress.IPv6Loopback, 0)).Result; var cb = new ClientBootstrap() .Channel<TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(100)) .Handler( new ActionChannelInitializer<TcpSocketChannel>( channel => { channel.Pipeline.AddLast(new FailAssertionHandler(clientError)); })) .Group(_clientGroup); var clientEp = s.LocalAddress; c = cb.ConnectAsync(clientEp).Result; c.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(2)).Wait(20); Assert.True(c.IsOpen); await c.CloseAsync(); // assert that the counters were never decremented Assert.True(clientError.Value == null, $"Expected null but error on client was {clientError.Value?.Message} {clientError.Value?.StackTrace}"); Assert.True(serverError.Value == null, $"Expected null but error on server was {serverError.Value?.Message} {serverError.Value?.StackTrace}"); } finally { try { c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200)); s?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200)); } catch { } } }
public void TcpSocketChannel_Flush_should_not_be_reentrant_after_Close() { // Skip for Mono due to Code Contracts assertions not working properly there if (MonotonicClock.IsMono) return; var eventLoopGroup = new MultithreadEventLoopGroup(1); try { var futures = new ConcurrentQueue<Task>(); var sb = new ServerBootstrap(); sb.Group(eventLoopGroup).Channel<TcpServerSocketChannel>().ChildOption(ChannelOption.SoSndbuf, 1024) .ChildHandler(new ChannelFlushCloseHandler(futures)); var address = (IPEndPoint) sb.BindAsync(IPAddress.IPv6Loopback, 0).Result.LocalAddress; var s = new System.Net.Sockets.Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); s.Connect(address.Address, address.Port); var inputStream = new NetworkStream(s, true); var buf = new byte[8192]; while (true) { var readBytes = inputStream.Read(buf, 0, 8192); if (readBytes == 0) { break; } // Wait a little bit so that the write attempts are split into multiple flush attempts. Thread.Sleep(10); } s.Close(); Assert.Equal(3, futures.Count); Task future1, future2, future3; futures.TryDequeue(out future1); futures.TryDequeue(out future2); futures.TryDequeue(out future3); Assert.True(future1.IsCompleted); Assert.False(future1.IsFaulted || future1.IsCanceled); Assert.True(future2.IsFaulted || future2.IsCanceled); Assert.IsType<ClosedChannelException>(future2.Exception.InnerException); Assert.True(future3.IsFaulted || future3.IsCanceled); Assert.IsType<ClosedChannelException>(future3.Exception.InnerException); } finally { eventLoopGroup.ShutdownGracefullyAsync(); } }
static async Task RunServerAsync() { var eventListener = new ObservableEventListener(); eventListener.LogToConsole(); eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose); var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup(); X509Certificate2 tlsCertificate = null; if (EchoServerSettings.IsSsl) { tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password"); } try { var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel<TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .Handler(new LoggingHandler(LogLevel.INFO)) .ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (tlsCertificate != null) { pipeline.AddLast(TlsHandler.Server(tlsCertificate)); } pipeline.AddLast(new LengthFieldPrepender(2)); pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); pipeline.AddLast(new EchoServerHandler()); })); IChannel bootstrapChannel = await bootstrap.BindAsync(EchoServerSettings.Port); Console.ReadLine(); await bootstrapChannel.CloseAsync(); } finally { Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync()); eventListener.Dispose(); } }
public TcpServerSocketChannelAndConnectionCompatSpecs() { _serverGroup = new MultithreadEventLoopGroup(1); _clientBootstrap = new ClientBootstrap() .SetTransport(TransportType.Tcp) .SetDecoder(new LengthFieldFrameBasedDecoder(int.MaxValue, 0, 4, 0, 4)) .SetEncoder(new LengthFieldPrepender(4, false)) .WorkerThreads(1).Build(); _serverBootstrap = new ServerBootstrap() .Channel<TcpServerSocketChannel>() .Group(_serverGroup) .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4, true)) .AddLast(new HeliosBackwardsCompatabilityLengthFramePrepender(4, false)) .AddLast(new EchoHandler()); })); }
public void SetUp(BenchmarkContext context) { this.ServerGroup = new MultithreadEventLoopGroup(1); this.WorkerGroup = new MultithreadEventLoopGroup(); Encoding iso = Encoding.GetEncoding("ISO-8859-1"); this.message = Unpooled.Buffer().WriteInt(3).WriteBytes(iso.GetBytes("ABC")).ToArray(); this.inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName); var counterHandler = new CounterHandlerInbound(this.inboundThroughputCounter); this.signal = new ManualResetEventSlimReadFinishedSignal(this.ResetEvent); // using default settings this.serverBufferAllocator = new PooledByteBufferAllocator(); ServerBootstrap sb = new ServerBootstrap() .Group(this.ServerGroup, this.WorkerGroup) .Channel<TcpServerSocketChannel>() .ChildOption(ChannelOption.Allocator, this.serverBufferAllocator) .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { channel.Pipeline .AddLast(this.GetEncoder()) .AddLast(this.GetDecoder()) .AddLast(counterHandler) .AddLast(new ReadFinishedHandler(this.signal, WriteCount)); })); // start server this.serverChannel = sb.BindAsync(TEST_ADDRESS).Result; // connect to server var address = (IPEndPoint)this.serverChannel.LocalAddress; this.ClientSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); this.ClientSocket.Connect(address.Address, address.Port); this.Stream = new NetworkStream(this.ClientSocket, true); }
/// <summary> /// 启动主机。 /// </summary> /// <param name="endPoint">主机终结点。</param> /// <returns>一个任务。</returns> public 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(_serializer, _serviceEntryLocate, _logger)); })); _channel = await bootstrap.BindAsync(endPoint); if (_logger.IsEnabled(LogLevel.Debug)) _logger.Debug($"服务主机启动成功,监听地址:{endPoint}。"); }
public void LocalChannel_PeerClose_when_WritePromiseComplete_in_same_eventloop_should_still_preserve_order() { var cb = new ClientBootstrap(); var sb = new ServerBootstrap(); var messageLatch = new CountdownEvent(2); var data = Unpooled.WrappedBuffer(new byte[1024]); var serverLatch = new CountdownEvent(1); var serverChannelRef = new AtomicReference<IChannel>(); try { cb.Group(_sharedGroup) .Channel<LocalChannel>() .Handler(new TestHandler()); sb.Group(_sharedGroup) .Channel<LocalServerChannel>() .ChildHandler(new ActionChannelInitializer<LocalChannel>(channel => { channel.Pipeline.AddLast(new ReadCountdown1(messageLatch, data)); serverChannelRef = channel; serverLatch.Signal(); })); IChannel sc = null; IChannel cc = null; try { // Start server sc = sb.BindAsync(TEST_ADDRESS).Result; // Connect to server cc = cb.ConnectAsync(sc.LocalAddress).Result; serverLatch.Wait(TimeSpan.FromSeconds(5)); Assert.True(serverLatch.IsSet); var ccCpy = cc; // Make sure a write operation is executed in the eventloop cc.Pipeline.LastContext().Executor.Execute(() => { ccCpy.WriteAndFlushAsync(data.Duplicate().Retain()).ContinueWith(tr => { var severChannelCopy = serverChannelRef.Value; severChannelCopy.CloseAsync(); }); }); Assert.True(messageLatch.Wait(TimeSpan.FromSeconds(5))); Assert.False(cc.IsOpen); Assert.False(serverChannelRef.Value.IsOpen); } finally { CloseChannel(sc); CloseChannel(cc); } } finally { data.Release(); } }
public void LocalChannel_write_when_WritePromiseComplete_should_still_preserve_order() { var cb = new ClientBootstrap(); var sb = new ServerBootstrap(); var messageLatch = new CountdownEvent(2); var data1 = Unpooled.WrappedBuffer(new byte[1024]); var data2 = Unpooled.WrappedBuffer(new byte[512]); try { cb.Group(_group1) .Channel<LocalChannel>() .Handler(new TestHandler()); sb.Group(_group2) .Channel<LocalServerChannel>() .ChildHandler(new ReadCountdown2(messageLatch, data1, data2)); IChannel sc = null; IChannel cc = null; try { // Start server sc = sb.BindAsync(TEST_ADDRESS).Result; // Connect to server cc = cb.ConnectAsync(sc.LocalAddress).Result; var ccCpy = cc; // Make sure a write operation is executed in the eventloop cc.Pipeline.LastContext().Executor.Execute(() => { Logger.Info("Writing message 1"); ccCpy.WriteAndFlushAsync(data1.Duplicate().Retain()).ContinueWith(tr => { Logger.Info("Writing message 2"); ccCpy.WriteAndFlushAsync(data2.Duplicate().Retain()); }); }); Assert.True(messageLatch.Wait(TimeSpan.FromSeconds(5))); } finally { CloseChannel(sc); CloseChannel(cc); } } finally { data1.Release(); data2.Release(); } }
public void LocalServerChannel_should_be_able_to_close_channel_on_same_EventLoop() { var latch = new CountdownEvent(1); var sb = new ServerBootstrap(); sb.Group(_group2).Channel<LocalServerChannel>().ChildHandler(new ReadHandler1(latch)); IChannel sc = null; IChannel cc = null; try { sc = sb.BindAsync(TEST_ADDRESS).Result; var b = new ClientBootstrap() .Group(_group2) .Channel<LocalChannel>().Handler(new ReadHandler2()); cc = b.ConnectAsync(sc.LocalAddress).Result; cc.WriteAndFlushAsync(new object()); Assert.True(latch.Wait(TimeSpan.FromSeconds(5))); } finally { CloseChannel(cc); CloseChannel(sc); } }
public void LocalChannel_WriteAsync_should_fail_fast_on_closed_channel() { var cb = new ClientBootstrap(); var sb = new ServerBootstrap(); cb.Group(_group1).Channel<LocalChannel>().Handler(new TestHandler()); sb.Group(_group2).Channel<LocalServerChannel>().ChildHandler(new ActionChannelInitializer<LocalChannel>( channel => { channel.Pipeline.AddLast(new TestHandler()); })); IChannel sc = null; IChannel cc = null; try { // Start server sc = sb.BindAsync(TEST_ADDRESS).Result; var latch = new CountdownEvent(1); // Connect to the server cc = cb.ConnectAsync(sc.LocalAddress).Result; // Close the channel and write something cc.CloseAsync().Wait(); var ag = Assert.Throws<AggregateException>(() => { cc.WriteAndFlushAsync(new object()).Wait(); }).Flatten(); Assert.IsType<ClosedChannelException>(ag.InnerException); } finally { CloseChannel(cc); CloseChannel(sc); } }
public void LocalChannel_should_reuse_LocalAddress() { for (var i = 0; i < 2; i++) { var cb = new ClientBootstrap(); var sb = new ServerBootstrap(); cb.Group(_group1).Channel<LocalChannel>().Handler(new TestHandler()); sb.Group(_group2).Channel<LocalServerChannel>().ChildHandler(new ActionChannelInitializer<LocalChannel>( channel => { channel.Pipeline.AddLast(new TestHandler()); })); IChannel sc = null; IChannel cc = null; try { // Start server sc = sb.BindAsync(TEST_ADDRESS).Result; var latch = new CountdownEvent(1); // Connect to the server cc = cb.ConnectAsync(sc.LocalAddress).Result; var cCpy = cc; cc.EventLoop.Execute(o => { var c = (LocalChannel) o; c.Pipeline.FireChannelRead("Hello, World"); latch.Signal(); }, cCpy); latch.Wait(TimeSpan.FromSeconds(5)); Assert.True(latch.IsSet); CloseChannel(cc); CloseChannel(sc); sc.CloseCompletion.Wait(); Assert.Null(LocalChannelRegistry.Get(TEST_ADDRESS)); } finally { CloseChannel(cc); CloseChannel(sc); } } }
/// <summary> /// Starts Echo server. /// </summary> /// <returns>function to trigger closure of the server.</returns> async Task<Func<Task>> StartServerAsync(bool tcpNoDelay, Action<IChannel> childHandlerSetupAction, TaskCompletionSource testPromise) { var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup(); bool started = false; //var tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password"); try { ServerBootstrap b = new ServerBootstrap() .Group(bossGroup, workerGroup) .Channel<TcpServerSocketChannel>() .Handler(new ExceptionCatchHandler(ex => testPromise.TrySetException(ex))) .ChildHandler(new ActionChannelInitializer<ISocketChannel>(childHandlerSetupAction)) .ChildOption(ChannelOption.TcpNodelay, tcpNoDelay); this.output.WriteLine("Configured ServerBootstrap: {0}", b); IChannel serverChannel = await b.BindAsync(Port); this.output.WriteLine("Bound server channel: {0}", serverChannel); started = true; return async () => { try { await serverChannel.CloseAsync(); } finally { Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync()); } }; } finally { if (!started) { Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync()); } } }
public Property TcpServerSocketChannel_can_accept_connection_on_any_valid_Endpoint(EndPoint ep) { var ip = ep as IPEndPoint; var family = ep.BestAddressFamily(); // TODO: remove this code once https://bugzilla.xamarin.com/show_bug.cgi?id=35536 is fixed if (IsMono && family == AddressFamily.InterNetworkV6 && ep is DnsEndPoint) { family = AddressFamily.InterNetwork; } IChannel s = null; IChannel c = null; try { var sb = new ServerBootstrap() .ChannelFactory(() => new TcpServerSocketChannel(family)) .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { })) .PreferredDnsResolutionFamily(family) .Group(_serverGroup); s = sb.BindAsync(ep).Result; var cb = new ClientBootstrap() .ChannelFactory(() => new TcpSocketChannel(family)) .Option(ChannelOption.TcpNodelay, true) .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(100)) .PreferredDnsResolutionFamily(family) .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel => { })) .Group(_clientGroup); var clientEp = s.LocalAddress; if (ip != null) // handle special case of 0.0.0.0, which clients can't connect to directly. { if (ip.Address.Equals(IPAddress.Any)) clientEp = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint) s.LocalAddress).Port); if (ip.Address.Equals(IPAddress.IPv6Any)) clientEp = new IPEndPoint(IPAddress.IPv6Loopback, ((IPEndPoint) s.LocalAddress).Port); } c = cb.ConnectAsync(clientEp).Result; c.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(2)).Wait(20); return c.IsOpen.Label("Channel should be open") .And(c.IsActive).Label("Channel should be active") .And(c.IsWritable).Label("Channel should be writable"); } finally { try { c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200)); s?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200)); } catch { } } }
public void SetUp(BenchmarkContext context) { TaskScheduler.UnobservedTaskException += (sender, args) => Console.WriteLine(args.Exception); this.ClientGroup = new MultithreadEventLoopGroup(1); this.ServerGroup = new MultithreadEventLoopGroup(1); this.WorkerGroup = new MultithreadEventLoopGroup(); Encoding iso = Encoding.GetEncoding("ISO-8859-1"); this.message = iso.GetBytes("ABC"); this.inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName); this.outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName); var counterHandler = new CounterHandlerInbound(this.inboundThroughputCounter); this.signal = new ManualResetEventSlimReadFinishedSignal(this.ResetEvent); // reserve up to 10mb of 16kb buffers on both client and server; we're only sending about 700k worth of messages this.serverBufferAllocator = new PooledByteBufferAllocator(); this.clientBufferAllocator = new PooledByteBufferAllocator(); Assembly assembly = typeof(TcpChannelPerfSpecs).Assembly; byte[] certificateData; using (Stream sourceStream = assembly.GetManifestResourceStream(assembly.GetManifestResourceNames()[0])) using (var tempStream = new MemoryStream()) { sourceStream.CopyTo(tempStream); certificateData = tempStream.ToArray(); } var tlsCertificate = new X509Certificate2(certificateData, "password"); string targetHost = tlsCertificate.GetNameInfo(X509NameType.DnsName, false); ServerBootstrap sb = new ServerBootstrap() .Group(this.ServerGroup, this.WorkerGroup) .Channel<TcpServerSocketChannel>() .ChildOption(ChannelOption.Allocator, this.serverBufferAllocator) .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { channel.Pipeline //.AddLast(TlsHandler.Server(tlsCertificate)) .AddLast(this.GetEncoder()) .AddLast(this.GetDecoder()) .AddLast(counterHandler) .AddLast(new CounterHandlerOutbound(this.outboundThroughputCounter)) .AddLast(new ReadFinishedHandler(this.signal, WriteCount)); })); Bootstrap cb = new Bootstrap() .Group(this.ClientGroup) .Channel<TcpSocketChannel>() .Option(ChannelOption.Allocator, this.clientBufferAllocator) .Handler(new ActionChannelInitializer<TcpSocketChannel>( channel => { channel.Pipeline //.AddLast(TlsHandler.Client(targetHost, null, (sender, certificate, chain, errors) => true)) .AddLast(this.GetEncoder()) .AddLast(this.GetDecoder()) .AddLast(counterHandler) .AddLast(new CounterHandlerOutbound(this.outboundThroughputCounter)); })); // start server this.serverChannel = sb.BindAsync(TEST_ADDRESS).Result; // connect to server this.clientChannel = cb.ConnectAsync(this.serverChannel.LocalAddress).Result; }
public void SetUp(BenchmarkContext context) { ServerGroup = new MultithreadEventLoopGroup(1); WorkerGroup = new MultithreadEventLoopGroup(); var iso = Encoding.GetEncoding("ISO-8859-1"); message = Unpooled.Buffer().WriteInt(3).WriteBytes(iso.GetBytes("ABC")).ToArray(); _inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName); _outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName); var counterHandler = new CounterHandlerInbound(_inboundThroughputCounter); _signal = new ManualResetEventSlimReadFinishedSignal(ResetEvent); var sb = new ServerBootstrap().Group(ServerGroup, WorkerGroup).Channel<TcpServerSocketChannel>() .ChildOption(ChannelOption.TcpNodelay, true) .ChildHandler( new ActionChannelInitializer<TcpSocketChannel>( channel => { channel.Pipeline.AddLast(GetEncoder()) .AddLast(GetDecoder()) .AddLast(counterHandler) .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter)) .AddLast(new ReadFinishedHandler(_signal, WriteCount)); })); // start server _serverChannel = sb.BindAsync(TEST_ADDRESS).Result; // connect to server var address = (IPEndPoint) _serverChannel.LocalAddress; ClientSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); ClientSocket.Connect(address.Address, address.Port); Stream = new NetworkStream(ClientSocket, true); }
public void SetUp(BenchmarkContext context) { ClientGroup = new MultithreadEventLoopGroup(1); ServerGroup = new MultithreadEventLoopGroup(1); WorkerGroup = new MultithreadEventLoopGroup(); var iso = Encoding.GetEncoding("ISO-8859-1"); message = iso.GetBytes("ABC"); // pre-allocate all messages foreach (var m in Enumerable.Range(0, WriteCount)) { messages[m] = Unpooled.WrappedBuffer(message); } _inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName); _outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName); var counterHandler = new CounterHandlerInbound(_inboundThroughputCounter); _signal = new ManualResetEventSlimReadFinishedSignal(ResetEvent); var sb = new ServerBootstrap().Group(ServerGroup, WorkerGroup).Channel<TcpServerSocketChannel>() .ChildOption(ChannelOption.TcpNodelay, true) .ChildHandler( new ActionChannelInitializer<TcpSocketChannel>( channel => { channel.Pipeline.AddLast(GetEncoder()) .AddLast(GetDecoder()) .AddLast(counterHandler) .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter)) .AddLast(new ReadFinishedHandler(_signal, WriteCount)); })); var cb = new ClientBootstrap().Group(ClientGroup) .Option(ChannelOption.TcpNodelay, true) .Channel<TcpSocketChannel>().Handler(new ActionChannelInitializer<TcpSocketChannel>( channel => { channel.Pipeline.AddLast(GetEncoder()).AddLast(GetDecoder()).AddLast(counterHandler) .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter)); })); // start server _serverChannel = sb.BindAsync(TEST_ADDRESS).Result; // connect to server _clientChannel = cb.ConnectAsync(_serverChannel.LocalAddress).Result; //_clientChannel.Configuration.AutoRead = false; }
public Property TcpSocketServerChannel_can_bind_on_any_valid_EndPoint(EndPoint ep) { IChannel c = null; var family = ep.BestAddressFamily(); // TODO: remove this code once https://bugzilla.xamarin.com/show_bug.cgi?id=35536 is fixed if (IsMono && family == AddressFamily.InterNetworkV6 && ep is DnsEndPoint) { family = AddressFamily.InterNetwork; } try { var sb = new ServerBootstrap() .ChannelFactory(() => new TcpServerSocketChannel(family)) .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { })) .PreferredDnsResolutionFamily(family) .Group(_serverGroup); c = sb.BindAsync(ep).Result; return c.IsOpen.Label("Channel should be open").And(c.IsActive).Label("Channel should be active"); } finally { c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200)); } }
public static Task<IChannel> CreateConnection(Role role, IPEndPoint socketAddress, int poolSize, IChannelHandler upstreamHandler) { if (role == Role.Client) { var connection = new ClientBootstrap() .ChannelFactory(() => new TcpSocketChannel(socketAddress.AddressFamily)) .Option(ChannelOption.TcpNodelay, true) .Group(GetClientWorkerPool(poolSize)) .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel => { ApplyChannelPipeline(channel, upstreamHandler); })); return connection.ConnectAsync(socketAddress); } else //server { var connection = new ServerBootstrap() .Group(GetServerPool(poolSize), GetServerWorkerPool(poolSize)) .ChannelFactory(() => new TcpServerSocketChannel(socketAddress.AddressFamily)) .ChildOption(ChannelOption.TcpNodelay, true) .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { ApplyChannelPipeline(channel, upstreamHandler); })); return connection.BindAsync(socketAddress); } }
public void LocalChannel_should_not_fire_channel_active_before_connecting() { var cb = new ClientBootstrap(); var sb = new ServerBootstrap(); cb.Group(_group1).Channel<LocalChannel>().Handler(new DummyHandler()); sb.Group(_group2).Channel<LocalServerChannel>().ChildHandler(new ActionChannelInitializer<LocalChannel>( channel => { channel.Pipeline.AddLast(new TestHandler()); })); IChannel sc = null; IChannel cc = null; try { // Start server sc = sb.BindAsync(TEST_ADDRESS).Result; cc = cb.Register().Result; var promise = new TaskCompletionSource(); var assertPromise = new TaskCompletionSource(); cc.Pipeline.AddLast(new PromiseAssertHandler(promise, assertPromise)); // Connect to the server cc.ConnectAsync(sc.LocalAddress).Wait(); assertPromise.Task.Wait(); Assert.True(promise.Task.IsCompleted); } finally { CloseChannel(cc); CloseChannel(sc); } }
public void LocalChannel_writes_to_server_should_be_read_by_LocalChannel() { var cb = new ClientBootstrap(); var sb = new ServerBootstrap(); var reads = new[] {-11, 2, 9, 13, 1013, 1, 4}; var resetEvent = new ManualResetEventSlim(); var accumulatedReads = new List<int>(); cb.Group(_group1) .Channel<LocalChannel>() .Handler( new ActionChannelInitializer<LocalChannel>( channel => { channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4)) .AddLast(new LengthFieldPrepender(4, false)) .AddLast(new IntCodec()); })); sb.Group(_group2) .Channel<LocalServerChannel>() .ChildHandler( new ActionChannelInitializer<LocalChannel>( channel => { channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(20, 0, 4, 0, 4)) .AddLast(new LengthFieldPrepender(4, false)) .AddLast(new IntCodec()) .AddLast(new ReadAssertHandler(accumulatedReads, resetEvent, reads)); })); IChannel sc = null; IChannel cc = null; try { // Start server sc = sb.BindAsync(TEST_ADDRESS).Result; // Connect to the server cc = cb.ConnectAsync(sc.LocalAddress).Result; foreach (var read in reads) { cc.WriteAsync(read); } cc.Flush(); resetEvent.Wait(200); Assert.Equal(reads, accumulatedReads); } finally { CloseChannel(sc); CloseChannel(cc); } }
public void SetUp(BenchmarkContext context) { ClientGroup = new MultithreadEventLoopGroup(1); ServerGroup = new MultithreadEventLoopGroup(2); var iso = Encoding.GetEncoding("ISO-8859-1"); message = iso.GetBytes("ABC"); _inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName); _outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName); var counterHandler = new CounterHandlerInbound(_inboundThroughputCounter); _signal = new SimpleReadFinishedSignal(); var sb = new ServerBootstrap().Group(ServerGroup).Channel<LocalServerChannel>() .ChildHandler( new ActionChannelInitializer<LocalChannel>( channel => { channel.Pipeline.AddLast(GetEncoder()) .AddLast(GetDecoder()) .AddLast(counterHandler) .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter)) .AddLast(new ReadFinishedHandler(_signal, WriteCount)); })); var cb = new ClientBootstrap().Group(ClientGroup) .Channel<LocalChannel>() .Handler(new ActionChannelInitializer<LocalChannel>( channel => { channel.Pipeline.AddLast(GetEncoder()).AddLast(GetDecoder()).AddLast(counterHandler) .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter)); })); // start server _serverChannel = sb.BindAsync(TEST_ADDRESS).Result; // connect to server _clientChannel = cb.ConnectAsync(_serverChannel.LocalAddress).Result; }
async Task EnsureServerInitializedAsync() { if (this.ServerAddress != null) { return; } int threadCount = Environment.ProcessorCount; var executorGroup = new MultithreadEventLoopGroup(threadCount); var bufAllocator = new PooledByteBufferAllocator(16 * 1024, 10 * 1024 * 1024 / threadCount); // reserve 10 MB for 64 KB buffers BlobSessionStatePersistenceProvider sessionStateProvider = await BlobSessionStatePersistenceProvider.CreateAsync( this.settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageConnectionString"), this.settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageContainerName")); TableQos2StatePersistenceProvider qos2StateProvider = await TableQos2StatePersistenceProvider.CreateAsync( this.settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageConnectionString"), this.settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageTableName")); var settings = new Settings(this.settingsProvider); var authProvider = new SasTokenAuthenticationProvider(); var topicNameRouter = new TopicNameRouter(); DeviceClientFactoryFunc deviceClientFactoryFactory = IotHubDeviceClient.PreparePoolFactory(settings.IotHubConnectionString + ";DeviceId=stub", "a", 1); ServerBootstrap server = new ServerBootstrap() .Group(executorGroup) .Channel<TcpServerSocketChannel>() .ChildOption(ChannelOption.Allocator, bufAllocator) .ChildOption(ChannelOption.AutoRead, false) .ChildHandler(new ActionChannelInitializer<IChannel>(ch => { ch.Pipeline.AddLast(TlsHandler.Server(this.tlsCertificate)); ch.Pipeline.AddLast( MqttEncoder.Instance, new MqttDecoder(true, 256 * 1024), new MqttIotHubAdapter( settings, deviceClientFactoryFactory, sessionStateProvider, authProvider, topicNameRouter, qos2StateProvider), new XUnitLoggingHandler(this.output)); })); IChannel serverChannel = await server.BindAsync(IPAddress.Any, this.ProtocolGatewayPort); this.ScheduleCleanup(async () => { await serverChannel.CloseAsync(); await executorGroup.ShutdownGracefullyAsync(); }); this.ServerAddress = IPAddress.Loopback; }
public void SetUp(BenchmarkContext context) { ClientGroup = new MultithreadEventLoopGroup(Environment.ProcessorCount/2); ServerGroup = new MultithreadEventLoopGroup(1); WorkerGroup = new MultithreadEventLoopGroup(Environment.ProcessorCount/2); _shutdownBenchmark = new CancellationTokenSource(); _clientChannels = new ConcurrentBag<IChannel>(); _inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName); _outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName); _clientConnectedCounter = context.GetCounter(ClientConnectCounterName); _errorCounter = context.GetCounter(ErrorCounterName); _signal = new ManualResetEventSlimReadFinishedSignal(ResetEvent); var sb = new ServerBootstrap().Group(ServerGroup, WorkerGroup).Channel<TcpServerSocketChannel>() .ChildOption(ChannelOption.TcpNodelay, true) .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { channel.Pipeline.AddLast(GetEncoder()) .AddLast(GetDecoder()) .AddLast(new IntCodec(true)) .AddLast(new CounterHandlerInbound(_inboundThroughputCounter)) .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter)) .AddLast(new ErrorCounterHandler(_errorCounter)); })); ClientBootstrap = new ClientBootstrap().Group(ClientGroup) .Option(ChannelOption.TcpNodelay, true) .Channel<TcpSocketChannel>().Handler(new ActionChannelInitializer<TcpSocketChannel>( channel => { channel.Pipeline.AddLast(GetEncoder()) .AddLast(GetDecoder()) .AddLast(new IntCodec(true)) .AddLast(new CounterHandlerInbound(_inboundThroughputCounter)) .AddLast(new CounterHandlerOutbound(_outboundThroughputCounter)) .AddLast(new ErrorCounterHandler(_errorCounter)); })); var token = _shutdownBenchmark.Token; _eventLoop = () => { while (!token.IsCancellationRequested) { foreach (var channel in _clientChannels) { // unrolling a loop channel.WriteAsync(ThreadLocalRandom.Current.Next()); channel.WriteAsync(ThreadLocalRandom.Current.Next()); channel.WriteAsync(ThreadLocalRandom.Current.Next()); channel.WriteAsync(ThreadLocalRandom.Current.Next()); channel.WriteAsync(ThreadLocalRandom.Current.Next()); channel.WriteAsync(ThreadLocalRandom.Current.Next()); channel.WriteAsync(ThreadLocalRandom.Current.Next()); channel.WriteAsync(ThreadLocalRandom.Current.Next()); channel.WriteAsync(ThreadLocalRandom.Current.Next()); channel.Flush(); } // sleep for a tiny bit, then get going again Thread.Sleep(40); } }; // start server _serverChannel = sb.BindAsync(TEST_ADDRESS).Result; // connect to server with 1 client initially _clientChannels.Add(ClientBootstrap.ConnectAsync(_serverChannel.LocalAddress).Result); }
public void TcpSocketServerChannel_can_be_connected_to_on_any_aliased_Endpoint(IpMapping actual, IpMapping alias, AddressFamily family) { var inboundActual = MappingToEndpoint(actual); var inboundAlias = MappingToEndpoint(alias); var isIp = inboundAlias is IPEndPoint; if (IsMono && family == AddressFamily.InterNetworkV6) { Assert.True(true, "Mono currently does not support IPV6 in DNS resolution"); return; } IChannel s = null; IChannel c = null; try { var sb = new ServerBootstrap() .ChannelFactory(() => new TcpServerSocketChannel()) .PreferredDnsResolutionFamily(family) .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel => { })) .Group(_serverGroup); s = sb.BindAsync(inboundActual).Result; var cb = new ClientBootstrap() .ChannelFactory(() => new TcpSocketChannel()) .Option(ChannelOption.TcpNodelay, true) .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(100)) .PreferredDnsResolutionFamily(family) .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel => { })) .Group(_clientGroup); EndPoint clientEp = isIp ? new IPEndPoint(((IPEndPoint) inboundAlias).Address, ((IPEndPoint) s.LocalAddress).Port) : (EndPoint) new DnsEndPoint(((DnsEndPoint) inboundAlias).Host, ((IPEndPoint) s.LocalAddress).Port); c = cb.ConnectAsync(clientEp).Result; c.WriteAndFlushAsync(Unpooled.Buffer(4).WriteInt(2)).Wait(20); Assert.True(c.IsOpen); Assert.True(c.IsActive); Assert.True(c.IsWritable); } finally { try { c?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200)); s?.CloseAsync().Wait(TimeSpan.FromMilliseconds(200)); } catch { } } }