ServerBootstrap SetupBootstrap(ChannelHandlerAdapter firstHandler) { Contract.Requires(firstHandler != null); return(new ServerBootstrap() .Group(this.parentEventLoopGroup, this.eventLoopGroup) .Option(ChannelOption.SoBacklog, ListenBacklogSize) .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .Channel <TcpServerSocketChannel>() .ChildHandler(new ActionChannelInitializer <IChannel>(channel => { int connectionPoolSize = this.settingsProvider.GetIntegerSetting("IotHubClient.ConnectionPoolSize", DefaultConnectionPoolSize); TimeSpan connectionIdleTimeout = this.settingsProvider.GetTimeSpanSetting("IotHubClient.ConnectionIdleTimeout", DefaultConnectionIdleTimeout); string connectionString = this.iotHubClientSettings.IotHubConnectionString; int maxInboundMessageSize = this.settingsProvider.GetIntegerSetting("MaxInboundMessageSize", 256 * 1024); var messagingAddressConverter = new IoTHubProvider.Addressing.MessageAddressConverter(); Func <IDeviceIdentity, Task <ITcpIoTHubMessagingServiceClient> > deviceClientFactory = IotHubClient.PreparePoolFactory(connectionString, connectionPoolSize, connectionIdleTimeout, this.iotHubClientSettings); MessagingBridgeFactoryFunc bridgeFactory = async deviceIdentity => new SingleClientMessagingBridge(deviceIdentity, await deviceClientFactory(deviceIdentity)); channel.Pipeline.AddLast(firstHandler); channel.Pipeline.AddLast(DeviceTopicDecoder.HandlerName, new DeviceTopicDecoder(this.credentialProvider, messagingAddressConverter.TopicTemplates)); channel.Pipeline.AddLast(SocketIoTHubAdapter.HandlerName, new SocketIoTHubAdapter(this.settings, credentialProvider, this.authProvider, bridgeFactory)); }))); }
public async Task RunClientAsync(ChannelHandlerAdapter channelHandler) { group = new MultithreadEventLoopGroup(); try { bootstrap = new Bootstrap(); bootstrap .Group(group) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler( new ActionChannelInitializer <ISocketChannel>( channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.AddLast("encoder", new ProtobufEncoder()); pipeline.AddLast(new ProtobufVarint32FrameDecoder()); pipeline.AddLast("decoder", new ProtobufDecoder(Message.Parser)); pipeline.AddLast("simple", channelHandler); })); clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port)); //await clientChannel.CloseAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { //await Task.WhenAll(group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))); } }
public async Task TestChannelInitializerInInitializerCorrectOrdering() { ChannelHandlerAdapter handler1 = new ChannelHandlerAdapter(); ChannelHandlerAdapter handler2 = new ChannelHandlerAdapter(); ChannelHandlerAdapter handler3 = new ChannelHandlerAdapter(); ChannelHandlerAdapter handler4 = new ChannelHandlerAdapter(); _client.Handler(new ActionChannelInitializer <IChannel>(ch => { ch.Pipeline.AddLast(handler1); ch.Pipeline.AddLast(new ActionChannelInitializer <IChannel>(ch0 => { ch0.Pipeline.AddLast(handler2); ch0.Pipeline.AddLast(handler3); })); ch.Pipeline.AddLast(handler4); })).LocalAddress(LocalAddress.Any); var channel = await _client.BindAsync(); try { // Execute some task on the EventLoop and wait until its done to be sure all handlers are added to the // pipeline. await channel.EventLoop.SubmitAsync(() => { // NOOP return(0); }); var handlers = channel.Pipeline.GetEnumerator(); Assert.True(handlers.MoveNext()); Assert.Same(handler1, handlers.Current); Assert.True(handlers.MoveNext()); Assert.Same(handler2, handlers.Current); Assert.True(handlers.MoveNext()); Assert.Same(handler3, handlers.Current); Assert.True(handlers.MoveNext()); Assert.Same(handler4, handlers.Current); Assert.False(handlers.MoveNext()); } finally { await channel.CloseAsync(); } }
public async Task RunAsync2(int threadCount, CancellationToken cancellationToken, X509Certificate2 cert = null, ServerTlsSettings serverTlsSettings = null, RemoteCertificateValidationCallback rcvb = null) { Contract.Requires(threadCount > 0); try { //BootstrapperEventSource.Log.Info("Starting", null); //PerformanceCounters.ConnectionsEstablishedTotal.RawValue = 0; //PerformanceCounters.ConnectionsCurrent.RawValue = 0; this.parentEventLoopGroup = new MultithreadEventLoopGroup(1); this.eventLoopGroup = new MultithreadEventLoopGroup(threadCount); ChannelHandlerAdapter handler = null; if (cert != null && serverTlsSettings != null) { handler = new TlsHandler(stream => new SslStream(stream, true, rcvb), serverTlsSettings); } else { handler = new DataBasedTenancyHandler(); } ServerBootstrap bootstrap = this.SetupBootstrap(handler); //BootstrapperEventSource.Log.Info($"Initializing TLS endpoint on port {this.settings.ListeningPort.ToString()} with certificate {this.tlsCertificate.Thumbprint}.", null); this.serverChannel = await bootstrap.BindAsync(IPAddress.Any, rcvb != null?this.settings.SecureListeningPort : this.settings.ListeningPort); 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(); } }
public static IClient Connect(URL url, params IChannelHandler[] handlers) { if (url == null) { throw new ArgumentNullException("url == null"); } IChannelHandler handler; if (handlers == null || handlers.Length == 0) { handler = new ChannelHandlerAdapter(); } else if (handlers.Length == 1) { handler = handlers[0]; } else { handler = new ChannelHandlerDispatcher(handlers); } return(GetTransporters().Connected(url, handler)); }
public AbstractTenancyContext(ISettingsProvider settingsProvider, TenantInfo tenancyData, IChannelHandlerContext channelContext, ChannelHandlerAdapter formatDecoder) { Contract.Requires(settingsProvider != null); this.settingsProvider = settingsProvider; this.TenantName = tenancyData?.TenantName; this.TenantId = tenancyData?.TenantId?.ToString(); this.TenantTrustInfo = tenancyData?.TenantTrustInfo; this.ChannelContext = channelContext; if (channelContext.Channel.Pipeline.Get("TenantDataFormatDecoder") == null) { channelContext.Channel.Pipeline.AddBefore(DeviceTopicDecoder.HandlerName, "TenantDataFormatDecoder", formatDecoder); } this.ChannelContext?.GetAttribute(this.attributeKey).Set(this); }
public async Task <bool> ConnectAsync(string ip, int port, ChannelHandlerAdapter channelHandler, params ByteToMessageDecoder[] decoders) { if (channelHandler == null) { throw new ArgumentNullException(nameof(channelHandler)); } if (!IPAddress.TryParse(ip, out IPAddress ipAddress)) { ipAddress = null; } if (ipAddress == null) { //Logger.Instance.Common.Info($"[ Netty ] ConnectAsync, Invalid IP Format, IP {ip}"); return(false); } try { _group = new MultithreadEventLoopGroup(); var bootstrap = new Bootstrap(); bootstrap.Group(_group) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, false) .Option(ChannelOption.SoKeepalive, true) .Option(ChannelOption.ConnectTimeout, TimeSpan.FromSeconds(10)) .Handler(new ActionChannelInitializer <ISocketChannel>(c => { var pipeline = c.Pipeline; if (decoders != null && decoders.Length > 0) { pipeline.AddLast(decoders); } pipeline.AddLast(channelHandler); })); _channel = await _bootstrap.ConnectAsync(new IPEndPoint(ipAddress, port)); if (_channel == null) { //Logger.Instance.Common.Info($"[ Netty ] ConnectAsync, IChannel Null, Address {ipAddress}:{port}"); return(false); } if (!_channel.Active) { await _channel.CloseAsync(); await _group.ShutdownGracefullyAsync(); //Logger.Instance.Common.Info($"[ Netty ] ConnectAsync, Connection Inactive, Address {ipAddress}:{port}"); return(false); } //Logger.Instance.Common.Info($"[ Netty ] ConnectAsync, Connection Succeeded, Address {ipAddress}:{port}"); return(true); } catch (Exception ex) { if (_channel != null) { await _channel.CloseAsync(); _channel = null; } if (_group != null) { await _group?.ShutdownGracefullyAsync(); _group = null; } //Logger.Instance.Common.Info($"[ Netty ] ConnectAsync, Connection Failed, Address {ipAddress}:{port}\nError:{ex.Message}"); return(false); } }
/// <summary> /// Bootstraps the Tcp IoT Hub Gateway /// </summary> /// <param name="certificate2">Server certificate for Tls</param> /// <param name="threadCount"># of threads to be used</param> /// <param name="cancellationToken">Cancellation flag</param> /// <returns></returns> public async Task RunAsync(int threadCount, CancellationToken cancellationToken, ChannelHandlerAdapter firstHandler, bool Tls = true) { Contract.Requires(threadCount > 0); try { //BootstrapperEventSource.Log.Info("Starting", null); //PerformanceCounters.ConnectionsEstablishedTotal.RawValue = 0; //PerformanceCounters.ConnectionsCurrent.RawValue = 0; this.parentEventLoopGroup = new MultithreadEventLoopGroup(1); this.eventLoopGroup = new MultithreadEventLoopGroup(threadCount); ServerBootstrap bootstrap = this.SetupBootstrap(firstHandler); //BootstrapperEventSource.Log.Info($"Initializing TLS endpoint on port {this.settings.ListeningPort.ToString()} with certificate {this.tlsCertificate.Thumbprint}.", null); this.serverChannel = await bootstrap.BindAsync(IPAddress.Any, Tls?this.settings.SecureListeningPort : this.settings.ListeningPort); 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(); } }