static async Task RunClientAsync() { var group = new MultithreadEventLoopGroup(); try { var bootstrap = new Bootstrap(); bootstrap.Group(group); bootstrap.Channel <TcpSocketChannel>(); bootstrap.Option(ChannelOption.TcpNodelay, true); bootstrap.Handler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddLast(new ProtobufVarint32FrameDecoder()); pipeline.AddLast(new ProtobufDecoder(Packet.Parser)); pipeline.AddLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.AddLast(new ProtobufEncoder()); pipeline.AddLast(new ClientHandler()); })); IChannel clientChannel = null; try { clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999)); } catch (AggregateException) { Console.WriteLine("Cannot connect to server"); return; } GameManager.instance.run(); await clientChannel.CloseAsync(); } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }
/// <summary> /// 创建Bootstrap /// </summary> /// <returns></returns> Bootstrap CreateBootStrap() { IEventLoopGroup group; var bootstrap = new Bootstrap(); group = new EventLoopGroup(); bootstrap.Channel <TcpChannel>(); bootstrap .Group(group) .Option(ChannelOption.TcpNodelay, true) .Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .Option(ChannelOption.ConnectTimeout, new TimeSpan(0, 0, 5)) .Handler(new ActionChannelInitializer <IChannel>(ch => { var pipeline = ch.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 RpcClientHandler(_logger, ReceiveMessage)); })); return(bootstrap); }
public async Task TestConnectDeadLock() { Bootstrap bootstrapA = new Bootstrap(); bootstrapA.Group(_groupA); bootstrapA.Channel <LocalChannel>(); bootstrapA.Handler(_dummyHandler); Bootstrap bootstrapB = new Bootstrap(); bootstrapB.Group(_groupB); bootstrapB.Channel <LocalChannel>(); bootstrapB.Handler(_dummyHandler); var bindFutures = new List <Task <int> >(); // Try to bind from each other. for (int i = 0; i < 1024; i++) { bindFutures.Add(_groupA.GetNext().SubmitAsync(() => { bootstrapB.ConnectAsync(LocalAddress.Any); return(i); })); bindFutures.Add(_groupB.GetNext().SubmitAsync(() => { bootstrapA.ConnectAsync(LocalAddress.Any); return(i); })); } for (int i = 0; i < bindFutures.Count; i++) { Task <int> result = bindFutures[i]; await result; } }
private void InitializeUdpChannel() { if (_logger.IsDebug) { _logger.Debug($"Discovery : udp://{_networkConfig.ExternalIp}:{_networkConfig.DiscoveryPort}"); } ThisNodeInfo.AddInfo("Discovery :", $"udp://{_networkConfig.ExternalIp}:{_networkConfig.DiscoveryPort}"); _group = new MultithreadEventLoopGroup(1); Bootstrap 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.LocalIp), _networkConfig.DiscoveryPort) .ContinueWith( t => { if (t.IsFaulted) { _logger.Error("Error when establishing discovery connection", t.Exception); } return(_channel = t.Result); }); }
private async Task <Bootstrap> createBootstrap(Bootstrap bootstrap, IEventLoopGroup eventLoop) { if (bootstrap != null) { bootstrap.Group(eventLoop); bootstrap.Channel <TcpSocketChannel>(); bootstrap.Option(ChannelOption.TcpNodelay, true); bootstrap.Option(ChannelOption.SoReuseaddr, true); if (!string.IsNullOrEmpty(localAddress)) { bootstrap.LocalAddress(new IPEndPoint(IPAddress.Parse(localAddress), localPort)); } bootstrap.Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast("reconnect", new ReconnectHandler(this)); pipeline.AddLast("One", new CardFrame()); // pipeline.AddLast("Two", new CardFile()); })); } while (true) { try { IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(remoteAddress), remotePort)); break; } catch (Exception e) { // Console.WriteLine(e.Message); Thread.Sleep(1000); } } return(bootstrap); }
public async Task RunAsync() { OnSubMessage?.Invoke("连接服务中......", "重要"); //第一步:创建ServerBootstrap实例 var bootstrap = new Bootstrap(); //第二步:绑定事件组 workGroup = new MultithreadEventLoopGroup(); bootstrap.Group(workGroup); //第三部:绑定通道 bootstrap.Channel <TcpSocketChannel>(); //第四步:配置处理器 bootstrap.Option(ChannelOption.TcpNodelay, true); var builder = new UriBuilder { Scheme = _clientConfig.IsWss ? "wss" : "ws", Host = _clientConfig.Host, Port = _clientConfig.Port, Path = _clientConfig.Path }; WebSocketClientHandshaker clientHandshaker = WebSocketClientHandshakerFactory.NewHandshaker(builder.Uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()); var handler = new ClientChannelHandler(clientHandshaker); bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(null))); pipeline.AddLast( new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.Instance, handler); })); Channel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(_clientConfig.Host), _clientConfig.Port)); await handler.HandshakeCompletion; }
public void Start() { try { _bootstrap.Group(_bossGroup); _bootstrap.Channel <TcpSocketChannel>(); _bootstrap.Option(ChannelOption.TcpNodelay, true); _bootstrap.Option(ChannelOption.SoKeepalive, true); _bootstrap.Option(ChannelOption.SoReuseport, true); _bootstrap.Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default); _bootstrap.Handler(new ActionChannelInitializer <ISocketChannel>((channel) => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast("DotNetty-enc", new LengthFieldPrepender(4)); pipeline.AddLast("DotNetty-dec", new LengthFieldBasedFrameDecoder(GlobalConfig.Config.MaxFrameLength, 0, 4, 0, 4)); pipeline.AddLast(new SlaveMessageHandler(this)); })); _connectThread.Start(); } catch (Exception ex) { Logger.Log.Error(true, "", ex); } }
public Boolean Init(ConnectionListener<string> listener, IPEndPoint localEndPoint, string certFile, string certPassword, bool fLoadWholeChain) { if (channel == null) { this._listener = listener; bootstrap = new Bootstrap(); loopGroup = new MultithreadEventLoopGroup(workerThreads); bootstrap.Group(loopGroup); bootstrap.Channel<SocketDatagramChannel>(); UDPClient currClient = this; bootstrap.Handler(new ActionChannelInitializer<SocketDatagramChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (isSecured) { Pkcs12Store keystore = null; if (certificate != null && certificate.Length > 0) keystore = CertificatesHelper.loadBC(certificate, certificatePassword); AsyncDtlsClient client = new MyAsyncDtlsClient(certFile, certPassword, fLoadWholeChain); _clientProtocol = new AsyncDtlsClientProtocol(client, new SecureRandom(), channel, currClient, true, ProtocolVersion.DTLSv12); pipeline.AddLast(new DtlsClientHandler(_clientProtocol, this)); } pipeline.AddLast("handler", new RawMessageHandler(listener)); #if false pipeline.AddLast(new CoapEncoder(channel)); pipeline.AddLast(new ExceptionHandler()); #endif })); bootstrap.RemoteAddress(address); #if true try { Task<IChannel> task; if (localEndPoint != null) { task = bootstrap.BindAsync(localEndPoint); } else { task = bootstrap.BindAsync(IPEndPoint.MinPort); } task.GetAwaiter().OnCompleted(() => { try { channel = task.Result; Task connectTask = channel.ConnectAsync(address); connectTask.GetAwaiter().OnCompleted(() => { if (_clientProtocol == null) { if (channel != null) listener.Connected(); else listener.ConnectFailed(); } else { startHandhshakeTimer(); _clientProtocol.InitHandshake(null); } }); } catch (Exception) { listener.ConnectFailed(); return; } }); } catch (Exception) { return false; } } #endif return true; }
private static Bootstrap GetBootstrap() { var bootstrap = new Bootstrap(); bootstrap .Channel<TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Group(new MultithreadEventLoopGroup()); return bootstrap; }
/// <summary>Connect to server /// </summary> public async ValueTask ConnectAsync() { if (_isConnected) { _logger.LogWarning("Socket client is connected , don't connect again !"); return; } try { _group = new MultithreadEventLoopGroup(_extraSetting.GroupEventLoopCount); _bootStrap = new Bootstrap(); _bootStrap.Group(_group); _bootStrap .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, _extraSetting.TcpNodelay) .Option(ChannelOption.SoKeepalive, _extraSetting.SoKeepalive) .Option(ChannelOption.WriteBufferHighWaterMark, _extraSetting.WriteBufferHighWaterMark) .Option(ChannelOption.WriteBufferLowWaterMark, _extraSetting.WriteBufferHighWaterMark) .Option(ChannelOption.SoRcvbuf, _extraSetting.SoRcvbuf) .Option(ChannelOption.SoSndbuf, _extraSetting.SoSndbuf) .Option(ChannelOption.SoReuseaddr, _extraSetting.SoReuseaddr) .Option(ChannelOption.AutoRead, _extraSetting.AutoRead) .Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (_extraSetting.IsSsl && _extraSetting.TlsCertificate != null) { //var targetHost = _setting.TlsCertificate.GetNameInfo(X509NameType.DnsName, false); //pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); } pipeline.AddLast("framing-enc", new LengthFieldPrepender(4)); pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4)); if (_setting.EnableHeartbeat) { pipeline.AddLast(new IdleStateHandler(_setting.HeartbeatInterval, _setting.HeartbeatInterval, _setting.HeartbeatInterval)); } pipeline.AddLast(new LoggingHandler(nameof(DotNettySocketClient))); pipeline.AddLast(new PacketDecoder(), new PacketEncoder()); if (_setting.EnableHeartbeat) { pipeline.AddLast("HeartbeatHandler", _app.ServiceProvider.CreateInstance <HeartbeatHandler>()); } //Handle PongPacket pipeline.AddLast("PongPacketHandler", _app.ServiceProvider.CreateInstance <PongPacketHandler>()); //Socket client Func <PushReqPacket, ValueTask> writePushReqPacketHandler = WritePushReqPacketAsync; Action <MessageRespPacket> setMessageRespPacketHandler = SetMessageRespPacket; Action channelWritabilityChangedHandler = ChannelWritabilityChanged; pipeline.AddLast("SocketClientHandler", _app.ServiceProvider.CreateInstance <SocketClientHandler>(writePushReqPacketHandler, setMessageRespPacketHandler, channelWritabilityChangedHandler)); if (_setting.EnableReConnect) { //Reconnect to server pipeline.AddLast("ReConnectHandler", _app.ServiceProvider.CreateInstance <ReConnectHandler>(_setting, new Func <Task>(DoReConnectAsync))); } })); await DoConnectAsync(); _isConnected = true; StartScanTimeoutRequestTask(); StartHandlePushReqPacketTask(); } catch (Exception ex) { _logger.LogError(ex.Message); await _group?.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(_setting.QuietPeriodMilliSeconds), TimeSpan.FromSeconds(_setting.CloseTimeoutSeconds)); } }
static async Task RunClientAsync() { var builder = new UriBuilder { Scheme = ClientSettings.IsSsl ? "wss" : "ws", Host = ClientSettings.Host.ToString(), Port = ClientSettings.Port }; string path = ExampleHelper.Configuration["path"]; if (!string.IsNullOrEmpty(path)) { builder.Path = path; } Uri uri = builder.Uri; ExampleHelper.SetConsoleLogger(); bool useLibuv = ClientSettings.UseLibuv; Console.WriteLine("Transport type : " + (useLibuv ? "Libuv" : "Socket")); IEventLoopGroup group; if (useLibuv) { group = new EventLoopGroup(); } else { group = new MultithreadEventLoopGroup(); } X509Certificate2 cert = null; string targetHost = null; if (ClientSettings.IsSsl) { cert = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password"); targetHost = cert.GetNameInfo(X509NameType.DnsName, false); } try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Option(ChannelOption.TcpNodelay, true); if (useLibuv) { bootstrap.Channel <TcpChannel>(); } else { bootstrap.Channel <TcpSocketChannel>(); } // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. var handler = new WebSocketClientHandler( WebSocketClientHandshakerFactory.NewHandshaker( uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders())); bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (cert != null) { pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); } pipeline.AddLast( new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.Instance, handler); })); IChannel ch = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port)); await handler.HandshakeCompletion; Console.WriteLine("WebSocket handshake completed.\n"); Console.WriteLine("\t[bye]:Quit \n\t [ping]:Send ping frame\n\t Enter any text and Enter: Send text frame"); while (true) { string msg = Console.ReadLine(); if (msg == null) { break; } else if ("bye".Equals(msg.ToLower())) { await ch.WriteAndFlushAsync(new CloseWebSocketFrame()); break; } else if ("ping".Equals(msg.ToLower())) { var frame = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 })); await ch.WriteAndFlushAsync(frame); } else { WebSocketFrame frame = new TextWebSocketFrame(msg); await ch.WriteAndFlushAsync(frame); } } await ch.CloseAsync(); } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }
private async Task<IChannel> ConnectAsync() { if (_logger.IsEnabled(LogLevel.Information)) _logger.Information($"准备连接到服务器:{_endPoint}。"); var bootstrap = new Bootstrap(); bootstrap .Channel<TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Group(new MultithreadEventLoopGroup()) .Handler(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 MessageReceiveHandler(_serialization, _resultDictionary, _logger)); })); var result = await bootstrap.ConnectAsync(_endPoint); if (_logger.IsEnabled(LogLevel.Information)) _logger.Information($"连接到服务器:{_endPoint},成功。"); return result; }
static async Task Main(string[] args) { ExampleHelper.SetConsoleLogger(); bool useLibuv = ClientSettings.UseLibuv; Console.WriteLine($"Transport type : {(useLibuv ? "Libuv" : "Socket")}"); IEventLoopGroup group; if (useLibuv) { group = new EventLoopGroup(); } else { group = new MultithreadEventLoopGroup(); } X509Certificate2 cert = null; string targetHost = null; if (ClientSettings.IsSsl) { cert = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password"); targetHost = cert.GetNameInfo(X509NameType.DnsName, false); } try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Option(ChannelOption.TcpNodelay, true); if (useLibuv) { bootstrap.Channel <TcpChannel>(); } else { bootstrap.Channel <TcpSocketChannel>(); } Http2ClientInitializer initializer = new Http2ClientInitializer(cert, targetHost, int.MaxValue); bootstrap.Handler(initializer); IChannel channel = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port)); try { Console.WriteLine($"Connected to [{ClientSettings.Host}:{ClientSettings.Port}]"); // Wait for the HTTP/2 upgrade to occur. Http2SettingsHandler http2SettingsHandler = initializer.SettingsHandler; await http2SettingsHandler.AwaitSettings(TimeSpan.FromSeconds(5)); HttpResponseHandler responseHandler = initializer.ResponseHandler; int streamId = 3; HttpScheme scheme = ClientSettings.IsSsl ? HttpScheme.Https : HttpScheme.Http; AsciiString hostName = new AsciiString(ClientSettings.Host.ToString() + ':' + ClientSettings.Port); Console.WriteLine("Sending request(s)..."); var url = ExampleHelper.Configuration["url"]; var url2 = ExampleHelper.Configuration["url2"]; var url2Data = ExampleHelper.Configuration["url2data"]; if (!string.IsNullOrEmpty(url)) { // Create a simple GET request. IFullHttpRequest request = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Get, url, Unpooled.Empty); request.Headers.Add(HttpHeaderNames.Host, hostName); request.Headers.Add(HttpConversionUtil.ExtensionHeaderNames.Scheme, scheme.Name); request.Headers.Add(HttpHeaderNames.AcceptEncoding, HttpHeaderValues.Gzip); request.Headers.Add(HttpHeaderNames.AcceptEncoding, HttpHeaderValues.Deflate); responseHandler.Put(streamId, channel.WriteAsync(request), channel.NewPromise()); streamId += 2; } if (!string.IsNullOrEmpty(url2)) { // Create a simple POST request with a body. IFullHttpRequest request = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Post, url2, Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(url2Data))); request.Headers.Add(HttpHeaderNames.Host, hostName); request.Headers.Add(HttpConversionUtil.ExtensionHeaderNames.Scheme, scheme.Name); request.Headers.Add(HttpHeaderNames.AcceptEncoding, HttpHeaderValues.Gzip); request.Headers.Add(HttpHeaderNames.AcceptEncoding, HttpHeaderValues.Deflate); responseHandler.Put(streamId, channel.WriteAsync(request), channel.NewPromise()); } channel.Flush(); await responseHandler.AwaitResponses(TimeSpan.FromSeconds(5)); Console.WriteLine("Finished HTTP/2 request(s)"); Console.ReadKey(); } catch (Exception exception) { Console.WriteLine(exception.ToString()); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { // Wait until the connection is closed. await channel.CloseAsync(); } } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }
void Start() { var builder = new UriBuilder { Scheme = "ws", Host = host, Port = port }; string path = "websocket"; if (!string.IsNullOrEmpty(path)) { builder.Path = path; } Uri uri = builder.Uri; IEventLoopGroup group; group = new MultithreadEventLoopGroup(); X509Certificate2 cert = null; string targetHost = null; //if (ClientSettings.IsSsl) //{ // cert = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password"); // targetHost = cert.GetNameInfo(X509NameType.DnsName, false); //} var bootstrap = new Bootstrap(); bootstrap .Group(group) .Option(ChannelOption.TcpNodelay, true); bootstrap.Channel <TcpSocketChannel>(); // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. var handler = new WebSocketClientHandler( WebSocketClientHandshakerFactory.NewHandshaker( uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()), allWaits, this); bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; //if (cert != null) //{ // pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); //} pipeline.AddLast( new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.Instance, handler); })); channel = bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(host), port)).Result; handler.HandshakeCompletion.Wait(); Console.WriteLine("WebSocket handshake completed."); pingWork = new CRL.Core.ThreadWork(); }
/// <summary> /// /// </summary> /// <param name="stoppingToken"></param> /// <returns></returns> public async Task Start(int port, IPEndPoint endPoint, CancellationToken stoppingToken) { IEventLoopGroup bossGroup; IEventLoopGroup workerGroup; IChannel boundChannel = null; bossGroup = new MultithreadEventLoopGroup(); workerGroup = new MultithreadEventLoopGroup(); var clientBossGroup = new MultithreadEventLoopGroup(); try { var bootstrap = new ServerBootstrap(); bootstrap.Group(bossGroup, workerGroup); bootstrap.Channel <TcpServerSocketChannel>(); var logEncoder = loggerFactory.CreateLogger <Encoder>(); var logDecoder = loggerFactory.CreateLogger <Decoder>(); bootstrap .Option(ChannelOption.SoBacklog, 100) .Handler(new LoggingHandler("SRV-LSTN")) .ChildHandler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; //pipeline.AddLast(new ReadTimeoutHandler(TimeSpan.FromSeconds(120))); pipeline.AddLast(new LoggingHandler("SRV-CONN")); pipeline.AddLast("framing-enc", new Encoder(logEncoder)); pipeline.AddLast("framing-dec", new Decoder(logDecoder)); pipeline.AddLast("echo", serviceProvider.GetService <ServerHandler>()); })); boundChannel = await bootstrap.BindAsync(port); log.LogInformation($"Bind: {port}"); clientBootstrap = new Bootstrap(); clientBootstrap.Group(clientBossGroup); clientBootstrap.Channel <TcpSocketChannel>(); clientBootstrap .Option(ChannelOption.TcpNodelay, true) .RemoteAddress(endPoint) .Handler(new LoggingHandler("SRV-LSTN")) .Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new LoggingHandler("SRV-CONN")); pipeline.AddLast("framing-enc", new Encoder(logEncoder)); pipeline.AddLast("framing-dec", new Decoder(logDecoder)); pipeline.AddLast("echo", serviceProvider.GetService <ClientHandler>()); })); log.LogInformation("waiting..."); Console.ReadLine(); await boundChannel.CloseAsync(); } finally { try { if (boundChannel != null) { await boundChannel.CloseAsync(); } } catch { } try { if (clientBossGroup != null) { await clientBossGroup.ShutdownGracefullyAsync(); } } catch { } await Task.WhenAll( bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)), workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))); } }
static async Task Main(string[] args) { ExampleHelper.SetConsoleLogger(); bool useLibuv = ClientSettings.UseLibuv; Console.WriteLine("Transport type : " + (useLibuv ? "Libuv" : "Socket")); IEventLoopGroup group; if (useLibuv) { group = new EventLoopGroup(); } else { group = new MultithreadEventLoopGroup(); } X509Certificate2 cert = null; string targetHost = null; if (ClientSettings.IsSsl) { cert = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password"); targetHost = cert.GetNameInfo(X509NameType.DnsName, false); } try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Option(ChannelOption.TcpNodelay, true) .Option(ChannelOption.SoKeepalive, true); if (useLibuv) { bootstrap.Channel <TcpChannel>(); } else { bootstrap.Channel <TcpSocketChannel>(); } bootstrap.Handler(new Http2ClientFrameInitializer(cert, targetHost)); IChannel channel = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port)); try { Console.WriteLine("Connected to [" + ClientSettings.Host + ':' + ClientSettings.Port + ']'); Http2ClientStreamFrameResponseHandler streamFrameResponseHandler = new Http2ClientStreamFrameResponseHandler(); Http2StreamChannelBootstrap streamChannelBootstrap = new Http2StreamChannelBootstrap(channel); IHttp2StreamChannel streamChannel = await streamChannelBootstrap.OpenAsync(); streamChannel.Pipeline.AddLast(streamFrameResponseHandler); // Send request (a HTTP/2 HEADERS frame - with ':method = GET' in this case) var path = ExampleHelper.Configuration["path"]; HttpScheme scheme = ClientSettings.IsSsl ? HttpScheme.Https : HttpScheme.Http; DefaultHttp2Headers headers = new DefaultHttp2Headers { Method = HttpMethod.Get.AsciiName, Path = AsciiString.Of(path), Scheme = scheme.Name }; IHttp2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(headers); await streamChannel.WriteAndFlushAsync(headersFrame); Console.WriteLine("Sent HTTP/2 GET request to " + path); // Wait for the responses (or for the latch to expire), then clean up the connections if (!streamFrameResponseHandler.ResponseSuccessfullyCompleted()) { Console.WriteLine("Did not get HTTP/2 response in expected time."); } Console.WriteLine("Finished HTTP/2 request, will close the connection."); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.WriteLine("按任意键退出"); Console.ReadKey(); } finally { // Wait until the connection is closed. await channel.CloseAsync(); } } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }
static async Task Main(string[] args) { var builder = new UriBuilder { Scheme = ClientSettings.IsSsl ? "https" : "http", Host = ClientSettings.Host.ToString(), Port = ClientSettings.Port, }; var baseUri = builder.Uri.ToString(); ExampleHelper.SetConsoleLogger(); string postSimple, postFile, get; if (baseUri.EndsWith("/")) { postSimple = baseUri + "formpost"; postFile = baseUri + "formpostmultipart"; get = baseUri + "formget"; } else { postSimple = baseUri + "/formpost"; postFile = baseUri + "/formpostmultipart"; get = baseUri + "/formget"; } var uriSimple = new Uri(postSimple); var uriFile = new Uri(postFile); bool useLibuv = ClientSettings.UseLibuv; Console.WriteLine("Transport type : " + (useLibuv ? "Libuv" : "Socket")); IEventLoopGroup group; if (useLibuv) { group = new EventLoopGroup(); } else { group = new MultithreadEventLoopGroup(); } X509Certificate2 cert = null; string targetHost = null; if (ClientSettings.IsSsl) { cert = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password"); targetHost = cert.GetNameInfo(X509NameType.DnsName, false); } try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Option(ChannelOption.TcpNodelay, true); if (useLibuv) { bootstrap.Channel <TcpChannel>(); } else { bootstrap.Channel <TcpSocketChannel>(); } bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (cert != null) { pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); } //pipeline.AddLast(new LoggingHandler("CONN")); pipeline.AddLast("codec", new HttpClientCodec()); // Remove the following line if you don't want automatic content decompression. pipeline.AddLast("inflater", new HttpContentDecompressor()); // to be used since huge file transfer pipeline.AddLast("chunkedWriter", new ChunkedWriteHandler <IHttpContent>()); pipeline.AddLast("handler", new HttpUploadClientHandler()); })); // setup the factory: here using a mixed memory/disk based on size threshold var factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MinSize); // Disk if MINSIZE exceed DiskFileUpload.DeleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskFileUpload.FileBaseDirectory = null; // system temp directory DiskAttribute.DeleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskAttribute.DiskBaseDirectory = null; // system temp directory // Simple Get form: no factory used (not usable) var headers = await FormgetAsync(bootstrap, get, uriSimple); if (headers == null) { factory.CleanAllHttpData(); return; } using (var file = new FileStream("upload.txt", FileMode.Open, FileAccess.Read)) { // Simple Post form: factory used for big attributes var bodylist = await FormpostAsync(bootstrap, uriSimple, file, factory, headers); if (bodylist == null) { factory.CleanAllHttpData(); return; } // Multipart Post form: factory used await FormpostmultipartAsync(bootstrap, uriFile, factory, headers, bodylist); } Console.WriteLine("按任意键退出"); Console.ReadKey(); } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }
public Boolean Init(ConnectionListener <AMQPHeader> listener) { if (channel == null) { bootstrap = new Bootstrap(); loopGroup = new MultithreadEventLoopGroup(workerThreads); bootstrap.Group(loopGroup); bootstrap.Channel <TcpSocketChannel>(); bootstrap.Option(ChannelOption.TcpNodelay, true); bootstrap.Option(ChannelOption.SoKeepalive, true); X509Certificate2 cert = null; if (certificate != null && certificate.Length > 0) { cert = CertificatesHelper.load(certificate, certificatePassword); } bootstrap.Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (isSecured) { if (cert != null) { pipeline.AddLast("ssl", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true, (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) => cert), new ClientTlsSettings(address.Host, new List <X509Certificate>() { cert }))); } else { pipeline.AddLast("ssl", TlsHandler.Client(address.Host)); } } pipeline.AddLast(new AMQPDecoder()); pipeline.AddLast("handler", new AMQPHandler(listener)); pipeline.AddLast(new AMQPEncoder()); pipeline.AddLast(new ExceptionHandler()); })); bootstrap.RemoteAddress(address); try { Task <IChannel> task = bootstrap.ConnectAsync(); task.GetAwaiter().OnCompleted(() => { try { channel = task.Result; } catch (Exception) { listener.ConnectFailed(); return; } if (channel != null) { listener.Connected(); } else { listener.ConnectFailed(); } }); } catch (Exception) { return(false); } } return(true); }
static async Task Main(string[] args) { var builder = new UriBuilder { Scheme = ClientSettings.IsSsl ? "wss" : "ws", Host = ClientSettings.Host.ToString(), Port = ClientSettings.Port, }; string path = ExampleHelper.Configuration["path"]; builder.Path = !string.IsNullOrEmpty(path) ? path : WEBSOCKET_PATH; Uri uri = builder.Uri; ExampleHelper.SetConsoleLogger(); bool useLibuv = ClientSettings.UseLibuv; Console.WriteLine("Transport type : " + (useLibuv ? "Libuv" : "Socket")); IEventLoopGroup group; if (useLibuv) { group = new EventLoopGroup(); } else { group = new MultithreadEventLoopGroup(); } X509Certificate2 cert = null; string targetHost = null; if (ClientSettings.IsSsl) { cert = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password"); targetHost = cert.GetNameInfo(X509NameType.DnsName, false); } try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Option(ChannelOption.TcpNodelay, true); if (useLibuv) { bootstrap.Channel <TcpChannel>(); } else { bootstrap.Channel <TcpSocketChannel>(); } // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. WebSocketClientHandler handler = new WebSocketClientHandler( WebSocketClientHandshakerFactory.NewHandshaker( uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders())); bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (cert != null) { pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); } pipeline.AddLast("idleStateHandler", new IdleStateHandler(0, 0, 60)); pipeline.AddLast(new LoggingHandler("CONN")); pipeline.AddLast( new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.Instance, //new WebSocketClientProtocolHandler( // webSocketUrl: uri, // version: WebSocketVersion.V13, // subprotocol: null, // allowExtensions: true, // customHeaders: new DefaultHttpHeaders(), // maxFramePayloadLength: 65536, // handleCloseFrames: true, // performMasking: false, // allowMaskMismatch: true, // enableUtf8Validator: false), new WebSocketFrameAggregator(65536), handler); })); try { IChannel ch = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port)); await handler.HandshakeCompletion; Console.WriteLine("WebSocket handshake completed.\n"); Console.WriteLine("\t[bye]:Quit \n\t [ping]:Send ping frame\n\t Enter any text and Enter: Send text frame"); while (true) { string msg = Console.ReadLine(); if (msg == null) { break; } msg = msg.ToLowerInvariant(); switch (msg) { case "bye": await ch.WriteAndFlushAsync(new CloseWebSocketFrame()); goto CloseLable; case "ping": var ping = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 })); await ch.WriteAndFlushAsync(ping); break; case "this is a test": await ch.WriteAndFlushManyAsync( new TextWebSocketFrame(false, "this "), new ContinuationWebSocketFrame(false, "is "), new ContinuationWebSocketFrame(false, "a "), new ContinuationWebSocketFrame(true, "test") ); break; case "this is a error": await ch.WriteAndFlushAsync(new TextWebSocketFrame(false, "this ")); await ch.WriteAndFlushAsync(new ContinuationWebSocketFrame(false, "is ")); await ch.WriteAndFlushAsync(new ContinuationWebSocketFrame(false, "a ")); await ch.WriteAndFlushAsync(new TextWebSocketFrame(true, "error")); break; default: await ch.WriteAndFlushAsync(new TextWebSocketFrame(msg)); break; } } CloseLable: await ch.CloseAsync(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.WriteLine("按任意键退出"); Console.ReadKey(); } } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }
private Task<IChannel> ConnectAsync() { var bootstrap = new Bootstrap(); bootstrap .Channel<TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Group(new MultithreadEventLoopGroup()) .Handler(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 MessageReceiveHandler(_serialization, _resultDictionary)); })); return bootstrap.ConnectAsync(_endPoint); }
/// <summary> /// Connect to a game and send ClientHello /// </summary> /// <param name="game"></param> /// <returns></returns> public async Task ConnectAsync(Enums.Game game) { PacketHandler = new PacketHandler(this); GameClient = new Client { TcpClient = this }; string host; switch (game) { case Enums.Game.ClashofClans: host = "gamea.clashofclans.com"; break; case Enums.Game.ClashRoyale: host = "game.clashroyaleapp.com"; break; case Enums.Game.BrawlStars: host = "game.brawlstarsgame.com"; break; case Enums.Game.HayDayPop: host = "game.prod.haydaypop.com"; break; case Enums.Game.BoomBeach: host = "game.boombeachgame.com"; break; case Enums.Game.HayDay: host = "game.haydaygame.com"; break; default: throw new ArgumentOutOfRangeException(nameof(game), game, null); } GameClient.CurrentGame = game; try { Bootstrap = new Bootstrap(); Bootstrap.Group(Group); Bootstrap.Channel <TcpSocketChannel>(); Bootstrap .Option(ChannelOption.TcpNodelay, true) .Option(ChannelOption.SoKeepalive, true) .Handler(new ActionChannelInitializer <IChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddFirst("FrameDecoder", new LengthFieldBasedFrameDecoder(int.MaxValue, 2, 3, 2, 0)); pipeline.AddLast("PacketHandler", PacketHandler); pipeline.AddLast("PacketEncoder", new PacketEncoder()); })); ServerChannel = await Bootstrap.ConnectAsync(host, 9339); /*var endpoint = (IPEndPoint) ServerChannel.RemoteAddress; * * Logger.Log( * $"Connected to {endpoint.Address.MapToIPv4()}:{endpoint.Port}.", Logger.ErrorLevel.Debug);*/ GameClient.Login(Resources.GameStatusManager.GetLatestFingerprintSha(game)); } catch (Exception exc) { Logger.Log( $"Failed to connect ({game}): {exc}", Logger.ErrorLevel.Warning); } }
public Boolean Init(ConnectionListener <SNMessage> listener) { if (channel == null) { this._listener = listener; bootstrap = new Bootstrap(); loopGroup = new MultithreadEventLoopGroup(workerThreads); bootstrap.Group(loopGroup); bootstrap.Channel <SocketDatagramChannel>(); UDPClient currClient = this; bootstrap.Handler(new ActionChannelInitializer <SocketDatagramChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (isSecured) { Pkcs12Store keystore = null; if (certificate != null && certificate.Length > 0) { keystore = CertificatesHelper.loadBC(certificate, certificatePassword); } AsyncDtlsClient client = new AsyncDtlsClient(keystore, certificatePassword, null); _clientProtocol = new AsyncDtlsClientProtocol(client, new SecureRandom(), channel, null, currClient, true, ProtocolVersion.DTLSv12); pipeline.AddLast(new DtlsClientHandler(_clientProtocol, this)); } pipeline.AddLast("handler", new SNHandler(listener)); pipeline.AddLast("encoder", new SNEncoder(channel)); pipeline.AddLast(new ExceptionHandler()); })); bootstrap.RemoteAddress(address); try { com.mobius.software.windows.iotbroker.mqtt_sn.net.UDPClient curr = this; Task <IChannel> task = bootstrap.BindAsync(IPEndPoint.MinPort); task.GetAwaiter().OnCompleted(() => { try { channel = task.Result; Task connectTask = channel.ConnectAsync(address); connectTask.GetAwaiter().OnCompleted(() => { if (_clientProtocol == null) { if (channel != null) { listener.Connected(); } else { listener.ConnectFailed(); } } else { startHandhshakeTimer(); _clientProtocol.InitHandshake(null); } }); } catch (Exception) { listener.ConnectFailed(); return; } }); } catch (Exception) { return(false); } } return(true); }
static async Task RunClientAsync() { var builder = new UriBuilder { Scheme = "ws", Host = "127.0.0.1", Port = 18089 }; string path = "websocket"; if (!string.IsNullOrEmpty(path)) { builder.Path = path; } Uri uri = builder.Uri; //ExampleHelper.SetConsoleLogger(); IEventLoopGroup group = new MultithreadEventLoopGroup(); try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Option(ChannelOption.TcpNodelay, true); bootstrap.Channel <TcpSocketChannel>(); // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. var handShaker = WebSocketClientHandshakerFactory.NewHandshaker( uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()); var channelGroup = new DefaultChannelGroup(null); bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast( new HttpClientCodec(), new HttpObjectAggregator(8192), //WebSocketClientCompressionHandler.Instance, new WebSocketClientProtocolHandler(handShaker, true), new BinaryWebSocketFrameHandler(), new ProtocolDecoder(), new ProtocolEncoder(), new MessageHandler(channelGroup)); pipeline.AddLast(new ProtocolEncoder()); })); IChannel ch = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 18089)); Console.WriteLine("WebSocket handshake completed.\n"); Console.WriteLine("\t[bye]:Quit \n\t [ping]:Send ping frame\n\t Enter any text and Enter: Send text frame"); while (true) { string msg = Console.ReadLine(); if (msg == null) { break; } else if ("bye".Equals(msg.ToLower())) { await ch.WriteAndFlushAsync(new CloseWebSocketFrame()); break; } else if ("ping".Equals(msg.ToLower())) { var frame = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 })); await ch.WriteAndFlushAsync(frame); } else { //WebSocketFrame frame = new TextWebSocketFrame(msg); //await ch.WriteAndFlushAsync(frame); var req = new LoginValidateRequest { Account = "sp001", Passwd = "111", ZoneId = 4 }; await ch.WriteAndFlushAsync(req); } } await ch.CloseAsync(); } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }
public Boolean Init(ConnectionListener <MQMessage> listener) { if (channel == null) { bootstrap = new Bootstrap(); loopGroup = new MultithreadEventLoopGroup(workerThreads); bootstrap.Group(loopGroup); bootstrap.Channel <TcpSocketChannel>(); bootstrap.Option(ChannelOption.TcpNodelay, true); bootstrap.Option(ChannelOption.SoKeepalive, true); X509Certificate2 cert = null; if (certificate != null && certificate.Length > 0) { cert = CertificatesHelper.load(certificate, certificatePassword); } WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.NewHandshaker(this.getUri(), WebSocketVersion.V13, null, false, EmptyHttpHeaders.Default, 1280000); WebSocketClientHandler handler = new WebSocketClientHandler(this, handshaker, listener); bootstrap.Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (isSecured) { if (cert != null) { pipeline.AddLast("ssl", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true, (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) => cert), new ClientTlsSettings(address.Host, new List <X509Certificate>() { cert }))); } else { pipeline.AddLast("ssl", TlsHandler.Client(address.Host)); } } pipeline.AddLast("http - codec", new HttpClientCodec()); pipeline.AddLast("aggregator", new HttpObjectAggregator(65536)); pipeline.AddLast("handler", handler); pipeline.AddLast(new ExceptionHandler()); })); bootstrap.RemoteAddress(address); try { Task <IChannel> task = bootstrap.ConnectAsync(); task.GetAwaiter().OnCompleted(() => { try { channel = task.Result; } catch (Exception) { listener.ConnectFailed(); return; } if (channel != null) { listener.Connected(); } else { listener.ConnectFailed(); } }); } catch (Exception) { return(false); } } return(true); }
public async Task ExecutorPreserveOrdering() { var sb = new ServerBootstrap(); sb.Group(new DefaultEventLoopGroup(1), new DefaultEventLoopGroup()); sb.Channel <LocalServerChannel>(); sb.ChildHandler(new ActionChannelInitializer <IChannel>(ch => { ch.Pipeline .AddLast(new HttpServerCodec()) .AddLast(new HttpObjectAggregator(1024)) .AddLast(/*compressorGroup,*/ new HttpContentCompressor()) .AddLast(new ChannelOutboundHandlerAdapter0()) .AddLast(new ChannelOutboundHandlerAdapter1()); })); var responses = new BlockingCollection <IHttpObject>(); var bs = new Bootstrap(); bs.Group(new DefaultEventLoopGroup()); bs.Channel <LocalChannel>(); bs.Handler(new ActionChannelInitializer <IChannel>(ch => { ch.Pipeline .AddLast(new HttpClientCodec()) .AddLast(new ChannelInboundHandlerAdapter0(responses)); })); IChannel serverChannel = null; IChannel clientChannel = null; try { serverChannel = await sb.BindAsync(new LocalAddress(Guid.NewGuid().ToString("N"))); clientChannel = await bs.ConnectAsync(serverChannel.LocalAddress); await clientChannel.WriteAndFlushAsync(NewRequest()); var result = responses.TryTake(out var item, TimeSpan.FromSeconds(1)); Assert.True(result); AssertEncodedResponse((IHttpResponse)item); result = responses.TryTake(out item, TimeSpan.FromSeconds(1)); Assert.True(result); IHttpContent c = (IHttpContent)item; Assert.NotNull(c); Assert.Equal($"1f8b08000000000000{Platform}f248cdc9c9d75108cf2fca4901000000ffff", ByteBufferUtil.HexDump(c.Content)); c.Release(); result = responses.TryTake(out item, TimeSpan.FromSeconds(1)); Assert.True(result); c = (IHttpContent)item; Assert.NotNull(c); Assert.Equal("0300c6865b260c000000", ByteBufferUtil.HexDump(c.Content)); c.Release(); result = responses.TryTake(out item, TimeSpan.FromSeconds(1)); Assert.True(result); ILastHttpContent last = (ILastHttpContent)item; Assert.NotNull(last); Assert.Equal(0, last.Content.ReadableBytes); last.Release(); Assert.False(responses.TryTake(out _, TimeSpan.FromSeconds(1))); } finally { if (clientChannel != null) { await clientChannel.CloseAsync(); } if (serverChannel != null) { await serverChannel.CloseAsync(); } await Task.WhenAll( sb.Group().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)), sb.ChildGroup().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)), bs.Group().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5))); } }
public async Task StartAsync(IPEndPoint address) { if (IsActive()) { throw new InvalidOperationException("Bootstrap is already active"); } _active = true; PacketHandlerRegistry.StartTicking(_packetHandlerTickingInterval); _bossGroup = new MultithreadEventLoopGroup(1); switch (BootstrapType) { case BootstrapTypeEnum.Server: try { _workerGroup = new MultithreadEventLoopGroup(); var bootstrap = new ServerBootstrap(); bootstrap.Group(_bossGroup, _workerGroup); bootstrap.Channel <TcpServerSocketChannel>(); bootstrap .Option(ChannelOption.SoBacklog, 100) .Handler(new DebugLoggingHandler(this)) .ChildHandler(GetChannelInitializer()); var boundChannel = await bootstrap.BindAsync(address); _logger.Info("Server bootstrap started"); while (_active) { await Task.Delay(200); } await boundChannel.CloseAsync(); } catch (Exception exe) { throw new BootstrapConnectionClosed("Bootstrap connection was unexpectedly closed", exe); } finally { await FinallyStopAsync(); } break; case BootstrapTypeEnum.Client: try { var bootstrap = new Bootstrap(); bootstrap.Group(_bossGroup); bootstrap.Channel <TcpSocketChannel>(); bootstrap .Handler(new DebugLoggingHandler(this)) .Handler(GetChannelInitializer()); await bootstrap.ConnectAsync(address); _logger.Info("Client bootstrap started"); while (_active) { await Task.Delay(200); } } catch (Exception exe) { throw new BootstrapConnectionClosed("Bootstrap connection was unexpectedly closed", exe); } finally { await FinallyStopAsync(); } break; default: throw new ArgumentOutOfRangeException(); } }