protected AbstractBootstrap(AbstractBootstrap <B, C> bootstrap) { _group = bootstrap.group(); _channelFactory = bootstrap.channelFactory(); _handler = bootstrap.handler(); _localAddress = bootstrap.localAddress(); }
public void ClientBootstrapLifetime() { var elg = new EventLoopGroup(1); var hostResolver = new DefaultHostResolver(elg); var bootstrap = new ClientBootstrap(elg, hostResolver); // When these go out of scope, the native handle will be released }
protected internal override void Stop0() { if (_channel == null) { return; } _debugLog.info(_serverName + ": stopping and unbinding from: " + _listenAddress); try { _channel.close().sync(); _channel = null; } catch (InterruptedException) { Thread.CurrentThread.Interrupt(); _debugLog.warn("Interrupted while closing channel."); } if (_workerGroup != null && _workerGroup.shutdownGracefully(2, 5, TimeUnit.SECONDS).awaitUninterruptibly(10, TimeUnit.SECONDS)) { _debugLog.warn("Worker group not shutdown within 10 seconds."); } _workerGroup = null; }
private static Bootstrap GetBootstrap() { IEventLoopGroup group; var bootstrap = new Bootstrap(); if (AppConfig.ServerOptions.Libuv) { group = new EventLoopGroup(); bootstrap.Channel <TcpServerChannel>(); } else { group = new MultithreadEventLoopGroup(); bootstrap.Channel <TcpServerSocketChannel>(); } bootstrap .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .Group(group); return(bootstrap); }
static void Main(string[] args) { ParseArgs(args); InitLogging(); InitOutput(); var tlsOptions = InitTls(); var elg = new EventLoopGroup(); var client = new ClientBootstrap(elg); try { var connectionTask = InitHttp(client, tlsOptions); var streamTask = InitStream(connectionTask.Result); var result = streamTask.Result; Console.WriteLine("Completed with code {0}", result.ErrorCode); } catch (AggregateException agg) // thrown by TaskCompletionSource { Console.Write("Operation failed: "); foreach (var ex in agg.Flatten().InnerExceptions) { Console.WriteLine(ex.Message); } Environment.Exit(-1); } finally { if (ctx.OutputStream != null) { ctx.OutputStream.Flush(); ctx.OutputStream.Close(); } } }
public void HostResolverLifetime() { var elg = new EventLoopGroup(1); var hostResolver = new DefaultHostResolver(elg, 8); // When hostResolver goes out of scope, the native handle will be released // Then elg should be released }
private static Bootstrap GetBootstrap() { IEventLoopGroup group; var bootstrap = new Bootstrap(); if (AppConfig.ServerOptions.Libuv) { group = new EventLoopGroup(); bootstrap.Channel <TcpServerChannel>(); } else { group = new MultithreadEventLoopGroup(); bootstrap.Channel <TcpServerSocketChannel>(); } bootstrap .Channel <TcpSocketChannel>() .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(AppConfig.ServerOptions.RpcConnectTimeout)) .Option(ChannelOption.TcpNodelay, true) .Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default) // .Option(ChannelOption.SoKeepalive,true) .Group(group); return(bootstrap); }
protected internal override void Start0() { if (_channel != null) { return; } _workerGroup = new NioEventLoopGroup(0, _threadFactory); ServerBootstrap bootstrap = (new ServerBootstrap()).group(_workerGroup).channel(typeof(NioServerSocketChannel)).option(ChannelOption.SO_REUSEADDR, true).localAddress(_listenAddress.socketAddress()).childHandler(_childInitializer.asChannelInitializer()); if (_parentHandler != null) { bootstrap.handler(_parentHandler); } try { _channel = bootstrap.bind().syncUninterruptibly().channel(); _debugLog.info(_serverName + ": bound to " + _listenAddress); } catch (Exception e) { //noinspection ConstantConditions netty sneaky throw if (e is BindException) { string message = _serverName + ": address is already bound: " + _listenAddress; _userLog.error(message); _debugLog.error(message, e); } throw e; } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton <IKeyValueCache <string, IChannel>, ChannelCache>(); // services.AddTransient<LoginHandler>(); services.AddTransient <PushMessageHandler>(); services.AddNettyService((services, bootstrap) => { /// <summary> /// /// </summary> var dispatcher = new DispatcherEventLoopGroup(); var bossGroup = dispatcher; var workGroup = new WorkerEventLoopGroup(dispatcher); var businessGroup = new EventLoopGroup(); bootstrap.Group(bossGroup, workGroup); /// 具体个选项的作用:https://blog.csdn.net/zuixiaoyao_001/article/details/90198968 bootstrap.Channel <TcpServerChannel>(); bootstrap.Option(ChannelOption.SoBacklog, 128); // 处理客户端连接的队列大小 bootstrap.Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(500)); // 连接超时时间 bootstrap.Option(ChannelOption.SoReuseaddr, true); // 允许重复使用本地地址和端口 bootstrap.Option(ChannelOption.SoKeepalive, true); // 如果在两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文 bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddLast("ACCEPT-LOG", new LoggingHandler()); // pipeline.AddLast("ACCEPT-CONN", services.GetRequiredService<LoginHandler>()); })); bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddLast(new ProtobufVarint32FrameDecoder()); pipeline.AddLast(new ProtobufDecoder(Options.Parser)); pipeline.AddLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.AddLast(new ProtobufEncoder()); pipeline.AddLast(businessGroup, services.GetRequiredService <PushMessageHandler>()); })); }); services.AddTransient <BaseDataUpdateService>(); services.AddMqClient("RabbitMq", Configuration); services.AddMqConsumerService((serviceProvider, mqClient) => { mqClient.ReceiveCommand <BaseDataUpdateCommand>(queue: string.Empty, resolve: () => serviceProvider.GetRequiredService <BaseDataUpdateService>().Handle, prefetchCount: 10); }); services.AddMemoryCache(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "NettyDemo", Version = "v1" }); }); }
public AbstractConnectionFactory(string ip, int port, string ns) { _ip = ip; _port = port; _ns = ns; _workGroup = new EventLoopGroup(4); _bootstrap = new Bootstrap(); _bootstrap.Group(_workGroup); }
public WebImageViewer(IPEndPoint address) { this.address = address; this.bossGroup = new NioEventLoopGroup(); this.workerGroup = new NioEventLoopGroup(); this.allChannels = new DefaultChannelGroup(GlobalEventExecutor.Instance); this.bootstrap = new ServerBootstrap().Group(bossGroup, workerGroup).Channel(typeof( NioServerSocketChannel)); }
// private Action enableAutoReadTask; public ServerBootstrapAcceptor(Channel channel, EventLoopGroup childGroup, ChannelHandler childHandler) { this.childGroup = childGroup; this.childHandler = childHandler; // Task which is scheduled to re-enable auto-read. // It's important to create this Runnable before we try to submit it as otherwise the URLClassLoader may // not be able to load the class because of the file limit it already reached. // // See https://github.com/netty/netty/issues/1328 // enableAutoReadTask = channel.config().setAutoRead(true); }
public virtual B group(EventLoopGroup _group) { if (_group == null) { throw new NullReferenceException("group"); } if (this._group != null) { throw new ArgumentException("group set already"); } this._group = _group; return((B)this); }
public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) { base.group(parentGroup); if (childGroup == null) { throw new NullReferenceException("childGroup"); } if (this.childGroup != null) { throw new ArgumentException("childGroup set already"); } this.childGroup = childGroup; return(this); }
private static Bootstrap GetBootstrap() { IEventLoopGroup group; var bootstrap = new Bootstrap(); group = new EventLoopGroup(); bootstrap.Channel <TcpServerChannel>(); bootstrap .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .Group(group); return(bootstrap); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public void start() throws Throwable public override void Start() { bool useEpoll = _useEpoll && Epoll.Available; ServerConfigurationProvider configurationProvider = useEpoll ? EpollConfigurationProvider.INSTANCE : NioConfigurationProvider.INSTANCE; _bossGroup = configurationProvider.CreateEventLoopGroup(1, _tf); // These threads handle live channels. Each thread has a set of channels it is responsible for, and it will // continuously run a #select() loop to react to new events on these channels. _selectorGroup = configurationProvider.CreateEventLoopGroup(_numSelectorThreads, _tf); // Bootstrap the various ports and protocols we want to handle foreach (KeyValuePair <BoltConnector, ProtocolInitializer> bootstrapEntry in _bootstrappersMap.SetOfKeyValuePairs()) { try { ProtocolInitializer protocolInitializer = bootstrapEntry.Value; BoltConnector boltConnector = bootstrapEntry.Key; ServerBootstrap serverBootstrap = CreateServerBootstrap(configurationProvider, protocolInitializer); ChannelFuture channelFuture = serverBootstrap.bind(protocolInitializer.Address().socketAddress()).sync(); InetSocketAddress localAddress = ( InetSocketAddress )channelFuture.channel().localAddress(); _connectionRegister.register(boltConnector.Key(), localAddress); string host = protocolInitializer.Address().Hostname; int port = localAddress.Port; if (host.Contains(":")) { // IPv6 _log.info("Bolt enabled on [%s]:%s.", host, port); } else { // IPv4 _log.info("Bolt enabled on %s:%s.", host, port); } } catch (Exception e) { // We catch throwable here because netty uses clever tricks to have method signatures that look like they do not // throw checked exceptions, but they actually do. The compiler won't let us catch them explicitly because in theory // they shouldn't be possible, so we have to catch Throwable and do our own checks to grab them throw new PortBindException(bootstrapEntry.Value.address(), e); } } }
public async Task DisconnectAsync() { Logger.LogTrace($"Stopping client.[{Channel.LocalAddress}]"); foreach (var task in _resultCallbackTask.Values) { task.TrySetCanceled(); } _resultCallbackTask.Clear(); if (Channel.Open) { await Channel.CloseAsync(); await EventLoopGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } Logger.LogTrace($"The client[{Channel.LocalAddress}] has stopped."); }
protected override void init(Channel _channel) { ChannelPipeline p = _channel.pipeline(); EventLoopGroup currentChildGroup = childGroup; ChannelHandler currentChildHandler = _childHandler; p.addLast(new ChannelInitializer <Channel>(channel => { ChannelPipeline pipeline = channel.pipeline(); ChannelHandler _handler = handler(); if (_handler != null) { pipeline.addLast(_handler); } channel.eventLoop().execute(() => pipeline.addLast(new ServerBootstrapAcceptor(channel, currentChildGroup, currentChildHandler))); })); }
public virtual String toString() { StringBuilder buf = new StringBuilder() .Append(this.GetType().Name) .Append('('); EventLoopGroup _group = group(); if (_group != null) { buf.Append("group: ") .Append(_group.GetType().Name) .Append(", "); } SocketAddress _localAddress = localAddress(); if (_localAddress != null) { buf.Append("localAddress: ") .Append(_localAddress) .Append(", "); } ChannelHandler _handler = handler(); if (_handler != null) { buf.Append("handler: ") .Append(_handler) .Append(", "); } if (buf[buf.Length - 1] == '(') { buf.Append(')'); } else { buf[buf.Length - 2] = ')'; buf.Length = (buf.Length - 1); } return(buf.ToString()); }
public void Start(int port, Dictionary <int, ProtocolCreator> factories) { _handlers.Add(GetOutputFile.ID, (s, p) => OnGetOutputFile(s, (GetOutputFile)p)); _handlers.Add(GenJob.ID, (s, p) => OnGenJob(s, (GenJob)p)); var worker = new EventLoopGroup(4, 16); var server = new TcpServerBootstrap { LocalAddress = new IPEndPoint(IPAddress.Any, port), ChildrenEventLoopGroup = worker, EventLoop = worker.ChooseEventLoop(), InitChildrenHandler = (s, c) => { c.Pipeline.AddLast(new ProtocolFrameCodec(20_000_000, new RecycleByteBufPool(100, 100), new DefaultProtocolAllocator(factories))); c.Pipeline.AddLast(this); } }; _ = server.ListenAsync(); }
private Bootstrap CreateBootstrap(bool useLibuv, out IEventLoopGroup group) { Logger.LogInformation($"\n{RuntimeInformation.OSArchitecture} {RuntimeInformation.OSDescription}" + $"\n{RuntimeInformation.ProcessArchitecture} {RuntimeInformation.FrameworkDescription}" + $"\nProcessor Count : {Environment.ProcessorCount}\n"); if (useLibuv) { group = new EventLoopGroup(); } else { group = new MultithreadEventLoopGroup(); } Logger.LogDebug("Transport type: " + (useLibuv ? "Libuv" : "Socket")); var bootstrap = new Bootstrap().Group(group); Logger.LogDebug($"Use group: {group.GetType().GetDisplayNameWithNamespace()}"); return(bootstrap); }
/// <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); }
/// <exception cref="System.IO.IOException"/> public DatanodeHttpServer(Configuration conf, DataNode datanode, ServerSocketChannel externalHttpChannel) { this.conf = conf; Configuration confForInfoServer = new Configuration(conf); confForInfoServer.SetInt(HttpServer2.HttpMaxThreads, 10); HttpServer2.Builder builder = new HttpServer2.Builder().SetName("datanode").SetConf (confForInfoServer).SetACL(new AccessControlList(conf.Get(DFSConfigKeys.DfsAdmin , " "))).HostName(GetHostnameForSpnegoPrincipal(confForInfoServer)).AddEndpoint( URI.Create("http://localhost:0")).SetFindPort(true); this.infoServer = builder.Build(); this.infoServer.AddInternalServlet(null, "/streamFile/*", typeof(StreamFile)); this.infoServer.AddInternalServlet(null, "/getFileChecksum/*", typeof(FileChecksumServlets.GetServlet )); this.infoServer.SetAttribute("datanode", datanode); this.infoServer.SetAttribute(JspHelper.CurrentConf, conf); this.infoServer.AddServlet(null, "/blockScannerReport", typeof(BlockScanner.Servlet )); this.infoServer.Start(); IPEndPoint jettyAddr = infoServer.GetConnectorAddress(0); this.confForCreate = new Configuration(conf); confForCreate.Set(FsPermission.UmaskLabel, "000"); this.bossGroup = new NioEventLoopGroup(); this.workerGroup = new NioEventLoopGroup(); this.externalHttpChannel = externalHttpChannel; HttpConfig.Policy policy = DFSUtil.GetHttpPolicy(conf); if (policy.IsHttpEnabled()) { this.httpServer = new ServerBootstrap().Group(bossGroup, workerGroup).ChildHandler (new _ChannelInitializer_117(this, jettyAddr, conf)); if (externalHttpChannel == null) { httpServer.Channel(typeof(NioServerSocketChannel)); } else { httpServer.ChannelFactory(new _ChannelFactory_130(externalHttpChannel)); } } else { // The channel has been bounded externally via JSVC, // thus bind() becomes a no-op. this.httpServer = null; } if (policy.IsHttpsEnabled()) { this.sslFactory = new SSLFactory(SSLFactory.Mode.Server, conf); try { sslFactory.Init(); } catch (GeneralSecurityException e) { throw new IOException(e); } this.httpsServer = new ServerBootstrap().Group(bossGroup, workerGroup).Channel(typeof( NioServerSocketChannel)).ChildHandler(new _ChannelInitializer_155(this, jettyAddr , conf)); } else { this.httpsServer = null; this.sslFactory = null; } }
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)); } }
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)); } }
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)); } }
protected SingleThreadEventLoop(EventLoopGroup parent, Executor executor, bool addTaskWakesUp, int maxPendingTasks) : base(parent, executor, addTaskWakesUp, maxPendingTasks) { tailTasks = newTaskQueue(maxPendingTasks); }
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)); } }
protected override void OnUnManDisposed() { _workGroup.Dispose(); _workGroup = null; _bootstrap = null; }