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();
            }
        }
Example #2
0
 private static IEventLoopGroup GetServerPool(int poolSize)
 {
     if (_serverPool == null)
     {
         _serverPool = new MultithreadEventLoopGroup(poolSize);
     }
     return _serverPool;
 }
Example #3
0
 private static IEventLoopGroup GetClientWorkerPool(int poolSize)
 {
     if (_clientPool == null)
     {
         _clientPool = new MultithreadEventLoopGroup(poolSize);
     }
     return _clientPool;
 }
 protected DeviceRunner(IEventLoopGroup eventLoopGroup, string deviceKey, string iotHubConnectionString, IPEndPoint endpoint, string tlsHostName)
 {
     this.deviceKey = deviceKey;
     this.endpoint = endpoint;
     this.tlsHostName = tlsHostName;
     this.connectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString.Contains("DeviceId=") ? iotHubConnectionString : iotHubConnectionString + ";DeviceId=abc");
     this.bootstrap = new Bootstrap()
         .Group(eventLoopGroup)
         .Channel<TcpSocketChannel>()
         .Option(ChannelOption.TcpNodelay, false);
 }
Example #5
0
        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 TcpSocketChannelAndReactorCompatSpecs()
        {
            _clientGroup = new MultithreadEventLoopGroup(1);
            _serverBootstrap = new ServerBootstrap()
                .SetTransport(TransportType.Tcp)
                .SetDecoder(new LengthFieldFrameBasedDecoder(int.MaxValue, 0, 4, 0, 4))
                .SetEncoder(new LengthFieldPrepender(4, false)).Build();

            _clientBootstrap = new ClientBootstrap()
                .Channel<TcpSocketChannel>()
                .Group(_clientGroup)
                .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel =>
                {
                    channel.Pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4, true))
                        .AddLast(new HeliosBackwardsCompatabilityLengthFramePrepender(4, false))
                        .AddLast(new ReadRecorderHandler(_received, _resetEvent, ReadCount));
                }));
        }
        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)
        {
            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;
        }
        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)
        {
            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);
        }
Example #11
0
 public DefaultEventLoop(IEventLoopGroup parent, IThreadFactory threadFactory, IRejectedExecutionHandler rejectedHandler, int maxPendingTasks)
     : base(parent, threadFactory, true, NewBlockingTaskQueue(maxPendingTasks), NewBlockingTaskQueue(maxPendingTasks), rejectedHandler)
 {
     Start();
 }
Example #12
0
 protected HeliosTransport(ActorSystem system, Config config)
 {
     Config = config;
     System = system;
     Settings = new HeliosTransportSettings(config);
     Log = Logging.GetLogger(System, GetType());
     _serverEventLoopGroup = new MultithreadEventLoopGroup(Settings.ServerSocketWorkerPoolSize);
     _clientEventLoopGroup = new MultithreadEventLoopGroup(Settings.ClientSocketWorkerPoolSize);
 }
Example #13
0
 public DefaultEventLoop(IEventLoopGroup parent, IRejectedExecutionHandler rejectedHandler, int maxPendingTasks)
     : this(parent, DefaultThreadFactory <DefaultEventLoop> .Instance, rejectedHandler, maxPendingTasks)
 {
 }
Example #14
0
 public DefaultEventLoop(IEventLoopGroup parent, IThreadFactory threadFactory, int maxPendingTasks)
     : this(parent, threadFactory, RejectedExecutionHandlers.Reject(), maxPendingTasks)
 {
 }
        private static void Main()
        {
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Converters = new List <JsonConverter> {
                    new IPEndPointConverter()
                }
            };

            var jsonlog = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "auth.json");
            var logfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "auth.log");

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File(new JsonFormatter(), jsonlog)
                         .WriteTo.File(logfile)
                         .WriteTo.Console(outputTemplate: "[{Level} {SourceContext}] {Message}{NewLine}{Exception}")
                         .MinimumLevel.Verbose()
                         .CreateLogger();

            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            TaskScheduler.UnobservedTaskException      += OnUnobservedTaskException;

            AuthDatabase.Initialize();

            Log.Information("Starting server...");

            AuthServer.Initialize(new Configuration());
            AuthServer.Instance.Listen(Config.Instance.Listener);

            s_apiEventLoopGroup = new MultithreadEventLoopGroup(2);
            s_loginapiHost      = new ServerBootstrap()
                                  .Group(s_apiEventLoopGroup)
                                  .Channel <TcpServerSocketChannel>()
                                  .Handler(new ActionChannelInitializer <IChannel>(ch => { }))
                                  .ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(new LoginServerHandler());
            }))
                                  .BindAsync(Config.Instance.AuthAPI.Listener).WaitEx();

            s_apiHost = new ServerBootstrap()
                        .Group(s_apiEventLoopGroup)
                        .Channel <TcpServerSocketChannel>()
                        .Handler(new ActionChannelInitializer <IChannel>(ch => { }))
                        .ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(new APIServerHandler());
            }))
                        .BindAsync(Config.Instance.API.Listener).WaitEx();

            Log.Information("Ready for connections!");

            if (Config.Instance.NoobMode)
            {
                Log.Warning("!!! NOOB MODE IS ENABLED! EVERY LOGIN SUCCEEDS AND OVERRIDES ACCOUNT LOGIN DETAILS !!!");
            }

            Console.CancelKeyPress += OnCancelKeyPress;
            while (true)
            {
                var input = Console.ReadLine();
                if (input == null)
                {
                    break;
                }

                if (input.Equals("exit", StringComparison.InvariantCultureIgnoreCase) ||
                    input.Equals("quit", StringComparison.InvariantCultureIgnoreCase) ||
                    input.Equals("stop", StringComparison.InvariantCultureIgnoreCase))
                {
                    break;
                }
            }

            Exit();
        }
Example #16
0
 public DefaultEventLoop(IEventLoopGroup parent, int maxPendingTasks)
     : this(parent, RejectedExecutionHandlers.Reject(), maxPendingTasks)
 {
 }
Example #17
0
 internal DispatcherEventLoop(IEventLoopGroup parent)
     : this(parent, DefaultThreadFactory <DispatcherEventLoop> .Instance)
 {
 }
        Func <IPAddress, int, Task <IChannel> > CreateWebSocketChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings)
        {
            return(async(address, port) =>
            {
                string additionalQueryParams = "";
#if WINDOWS_UWP || NETSTANDARD1_3
                // UWP and NETSTANDARD1_3 implementation doesn't set client certs, so we want to tell the IoT Hub to not ask for them
                additionalQueryParams = "?iothub-no-client-cert=true";
#endif
                IEventLoopGroup eventLoopGroup = EventLoopGroupPool.TakeOrAdd(this.eventLoopGroupKey);

                var websocketUri = new Uri(WebSocketConstants.Scheme + iotHubConnectionString.HostName + ":" + WebSocketConstants.SecurePort + WebSocketConstants.UriSuffix + additionalQueryParams);
                var websocket = new ClientWebSocket();
                websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Mqtt);

#if !WINDOWS_UWP // UWP does not support proxies
                // Check if we're configured to use a proxy server
                IWebProxy webProxy = WebRequest.DefaultWebProxy;
                Uri proxyAddress = null;
#if !NETSTANDARD1_3
                proxyAddress = webProxy?.GetProxy(websocketUri);
#endif
                if (!websocketUri.Equals(proxyAddress))
                {
                    // Configure proxy server
                    websocket.Options.Proxy = webProxy;
                }
#endif

                if (settings.ClientCertificate != null)
                {
                    websocket.Options.ClientCertificates.Add(settings.ClientCertificate);
                }
#if !WINDOWS_UWP && !NETSTANDARD1_3 // UseDefaultCredentials is not in UWP and NetStandard
                else
                {
                    websocket.Options.UseDefaultCredentials = true;
                }
#endif

                using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
                {
                    await websocket.ConnectAsync(websocketUri, cancellationTokenSource.Token);
                }

#if WINDOWS_UWP
                PlatformProvider.Platform = new UWPPlatform();
#endif
                var clientChannel = new ClientWebSocketChannel(null, websocket);
                clientChannel
                .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                .Option(ChannelOption.AutoRead, false)
                .Option(ChannelOption.RcvbufAllocator, new AdaptiveRecvByteBufAllocator())
                .Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default)
                .Pipeline.AddLast(
                    MqttEncoder.Instance,
                    new MqttDecoder(false, MaxMessageSize),
                    this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings));
                await eventLoopGroup.GetNext().RegisterAsync(clientChannel);

                this.ScheduleCleanup(() =>
                {
                    EventLoopGroupPool.Release(this.eventLoopGroupKey);
                    return TaskConstants.Completed;
                });

                return clientChannel;
            });
        }
Example #19
0
 public LocalChannelTest()
 {
     _group1      = new MultithreadEventLoopGroup(2);
     _group2      = new MultithreadEventLoopGroup(2);
     _sharedGroup = new MultithreadEventLoopGroup(1);
 }
Example #20
0
 public LocalChannelTest()
 {
     _group1 = new MultithreadEventLoopGroup(2);
     _group2 = new MultithreadEventLoopGroup(2);
     _sharedGroup = new MultithreadEventLoopGroup(1);
 }
 public FlowControlHandlerTest()
 {
     this.group = new MultithreadEventLoopGroup();
 }
        /// <summary>
        /// 创建 TCP 协议封装器。
        /// </summary>
        /// <param name="factory">给定的 <see cref="IBootstrapWrapperFactory"/>。</param>
        /// <param name="useLibuv">使用 LIBUV。</param>
        /// <param name="group">输出 <see cref="IEventLoopGroup"/>。</param>
        /// <returns>返回 <see cref="IBootstrapWrapper"/>。</returns>
        public static IBootstrapWrapper CreateTcp(this IBootstrapWrapperFactory factory, bool useLibuv, out IEventLoopGroup group)
        => factory.NotNull(nameof(factory))
        .Create(useLibuv, out group)
        .Configure(bootstrap =>
        {
            bootstrap.Option(ChannelOption.TcpNodelay, true);

            if (useLibuv)
            {
                bootstrap.Channel <TcpChannel>();
            }
            else
            {
                bootstrap.Channel <TcpSocketChannel>();
            }
        });
        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;
        }
        /// <summary>
        /// 创建 TCP 协议服务端封装器。
        /// </summary>
        /// <param name="factory">给定的 <see cref="IBootstrapWrapperFactory"/>。</param>
        /// <param name="useLibuv">使用 LIBUV。</param>
        /// <param name="bossGroup">输出引领 <see cref="IEventLoopGroup"/>。</param>
        /// <param name="workerGroup">输出工作 <see cref="IEventLoopGroup"/>。</param>
        /// <returns>返回 <see cref="IServerBootstrapWrapper"/>。</returns>
        public static IServerBootstrapWrapper CreateTcpServer(this IBootstrapWrapperFactory factory, bool useLibuv,
                                                              out IEventLoopGroup bossGroup, out IEventLoopGroup workerGroup)
        => factory.NotNull(nameof(factory))
        .CreateServer(useLibuv, out bossGroup, out workerGroup)
        .Configure(bootstrap =>
        {
            if (useLibuv)
            {
                bootstrap.Channel <TcpServerChannel>();

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                    RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    bootstrap
                    .Option(ChannelOption.SoReuseport, true)
                    .ChildOption(ChannelOption.SoReuseaddr, true);

                    factory.Logger.LogInformation($"Run in {Environment.OSVersion.Platform}");
                }
            }
            else
            {
                bootstrap.Channel <TcpServerSocketChannel>();
            }
        });
Example #25
0
        private static void Main()
        {
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Converters = new List <JsonConverter> {
                    new IPEndPointConverter()
                }
            };

            var jsonlog = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AuthServer.json");
            var logfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AuthServer.log");

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File(new JsonFormatter(), jsonlog)
                         .WriteTo.File(logfile)
                         .WriteTo.Console(outputTemplate: "[{Level} {SourceContext}] {Message}{NewLine}{Exception}")
                         .MinimumLevel.Verbose()
                         .CreateLogger();
            var Logger = Log.ForContext(Constants.SourceContextPropertyName, "Initialiazor");

            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            TaskScheduler.UnobservedTaskException      += OnUnobservedTaskException;

            AuthDatabase.Initialize();

            Logger.Information("Starting server...");

            if (!Directory.Exists("XBN"))
            {
                throw new Exception("XBN folder is missing!");
            }

            foreach (var xbn in Enum.GetValues(typeof(XBNType)).Cast <XBNType>().ToList())
            {
                var name = $"XBN//{xbn.ToString()}.xbn";
                if (File.Exists(name))
                {
                    var data = File.ReadAllBytes(name);
                    XBNdata.TryAdd(xbn, data);
                    Logger.Information($"Cached xbnfile: {name}");
                }
            }


            Network.AuthServer.Initialize(new Configuration());
            Network.AuthServer.Instance.Listen(Config.Instance.Listener);

            s_apiEventLoopGroup = new MultithreadEventLoopGroup(2);
            s_loginapiHost      = new ServerBootstrap()
                                  .Group(s_apiEventLoopGroup)
                                  .Channel <TcpServerSocketChannel>()
                                  .Handler(new ActionChannelInitializer <IChannel>(ch => { }))
                                  .ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(new LoginServerHandler());
            }))
                                  .BindAsync(Config.Instance.AuthAPI.Listener).WaitEx();
            s_apiHost = new ServerBootstrap()
                        .Group(s_apiEventLoopGroup)
                        .Channel <TcpServerSocketChannel>()
                        .Handler(new ActionChannelInitializer <IChannel>(ch => { }))
                        .ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(new APIServerHandler());
            }))
                        .BindAsync(Config.Instance.API.Listener).WaitEx();

            Logger.Information("Ready for connections!");

            if (Config.Instance.NoobMode)
            {
                Logger.Warning(
                    "!!! NOOB MODE IS ENABLED! EVERY LOGIN SUCCEEDS AND OVERRIDES ACCOUNT LOGIN DETAILS !!!");
            }

            Console.CancelKeyPress += OnCancelKeyPress;
            while (true)
            {
                var input = Console.ReadLine();
                if (input == null)
                {
                    break;
                }

                if (input.Equals("exit", StringComparison.InvariantCultureIgnoreCase) ||
                    input.Equals("quit", StringComparison.InvariantCultureIgnoreCase) ||
                    input.Equals("stop", StringComparison.InvariantCultureIgnoreCase))
                {
                    break;
                }
            }

            Exit();
        }
Example #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XmppClient"/> class.
 /// </summary>
 /// <param name="pipelineInitializerAction">The pipeline initializer action.</param>
 /// <param name="eventLoopGroup">The event loop group.</param>
 public XmppClient(Action <IChannelPipeline, ISession> pipelineInitializerAction, IEventLoopGroup eventLoopGroup)
     : base(pipelineInitializerAction, eventLoopGroup)
 {
 }
Example #27
0
        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;
            var      tlsCertificate = TestResourceHelper.GetTestCertificate();
            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;
        }
Example #28
0
 public ServerChannelHandler(IServerChannelFactory factory, IEventLoopGroup childLoopGroup, IChannelHandler childhandler)
 {
     mChildHandler   = childhandler;
     mChildLoopGroup = childLoopGroup;
     mFactory        = factory;
 }
Example #29
0
 /// <summary>
 /// Creates a new instance of <see cref="AffinitizedEventLoopGroup"/>.
 /// </summary>
 /// <param name="innerGroup"><see cref="IEventLoopGroup"/> serving as an actual provider of <see cref="IEventLoop"/>s.</param>
 public AffinitizedEventLoopGroup(IEventLoopGroup innerGroup)
 {
     this.innerGroup = innerGroup;
 }
Example #30
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

            Console.WriteLine(
                $"\n{RuntimeInformation.OSArchitecture} {RuntimeInformation.OSDescription}"
                + $"\n{RuntimeInformation.ProcessArchitecture} {RuntimeInformation.FrameworkDescription}"
                + $"\nProcessor Count : {Environment.ProcessorCount}\n");

            bool useLibuv = ServerSettings.UseLibuv;

            Console.WriteLine("Transport type : " + (useLibuv ? "Libuv" : "Socket"));

            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            }

            Console.WriteLine($"Server garbage collection : {(GCSettings.IsServerGC ? "Enabled" : "Disabled")}");
            Console.WriteLine($"Current latency mode for garbage collection: {GCSettings.LatencyMode}");
            Console.WriteLine("\n");

            IEventLoopGroup bossGroup;
            IEventLoopGroup workGroup;
            IEventLoopGroup bossGroup2 = null;
            IEventLoopGroup workGroup2 = null;

            if (useLibuv)
            {
                var dispatcher = new DispatcherEventLoopGroup();
                bossGroup = dispatcher;
                workGroup = new WorkerEventLoopGroup(dispatcher);

                dispatcher = new DispatcherEventLoopGroup();
                bossGroup2 = dispatcher;
                workGroup2 = new WorkerEventLoopGroup(dispatcher);
            }
            else
            {
                bossGroup = new MultithreadEventLoopGroup(1);
                workGroup = new MultithreadEventLoopGroup();
            }

            IChannel http2Channel = null;
            IChannel httpChannel  = null;

            try
            {
                Http2Server http2 = useLibuv ? new Http2Server(bossGroup2, workGroup2) : new Http2Server(bossGroup, workGroup);
                http2Channel = await http2.StartAsync();

                Console.WriteLine("Open your web browser and navigate to " + "http://127.0.0.1:" + HttpServer.PORT);
                HttpServer http = new HttpServer(bossGroup, workGroup);
                httpChannel = await http.StartAsync();

                Console.WriteLine("按任意键退出");
                Console.ReadKey();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.ToString());
                Console.ReadKey();
            }
            finally
            {
                if (http2Channel != null)
                {
                    await http2Channel.CloseAsync();
                }
                if (httpChannel != null)
                {
                    await httpChannel.CloseAsync();
                }

                if (workGroup2 != null)
                {
                    await workGroup2.ShutdownGracefullyAsync();
                }
                if (bossGroup2 != null)
                {
                    await bossGroup2.ShutdownGracefullyAsync();
                }
                await workGroup.ShutdownGracefullyAsync();

                await bossGroup.ShutdownGracefullyAsync();
            }
        }
        /// <summary>Run socket server
        /// </summary>
        public async ValueTask RunAsync()
        {
            if (_boundChannel != null)
            {
                _logger.LogInformation($"Server is running! Don't run again! ChannelId:{_boundChannel.Id.AsShortText()}");
                return;
            }
            _bossGroup   = new MultithreadEventLoopGroup(_extraSetting.BossGroupEventLoopCount);
            _workerGroup = new MultithreadEventLoopGroup(_extraSetting.WorkGroupEventLoopCount);

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(_bossGroup, _workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, _extraSetting.SoBacklog)
                .ChildOption(ChannelOption.TcpNodelay, _extraSetting.TcpNodelay)
                .ChildOption(ChannelOption.WriteBufferHighWaterMark, _extraSetting.WriteBufferHighWaterMark)
                .ChildOption(ChannelOption.WriteBufferLowWaterMark, _extraSetting.WriteBufferLowWaterMark)
                .ChildOption(ChannelOption.SoRcvbuf, _extraSetting.SoRcvbuf)
                .ChildOption(ChannelOption.SoSndbuf, _extraSetting.SoSndbuf)
                .ChildOption(ChannelOption.SoReuseaddr, _extraSetting.SoReuseaddr)
                .ChildOption(ChannelOption.AutoRead, _extraSetting.AutoRead)
                .Handler(new LoggingHandler(nameof(DotNettySocketServer)))
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    //if (_setting.IsSsl && _setting.TlsCertificate != null)
                    //{
                    //    pipeline.AddLast("tls", TlsHandler.Server(_setting.TlsCertificate));
                    //}

                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(4));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));

                    //coder and encoder
                    pipeline.AddLast(new PacketDecoder(), new PacketEncoder());

                    //Handle PingPacket
                    pipeline.AddLast("PingPacketHandler", _app.ServiceProvider.CreateInstance <PingPacketHandler>());

                    //SocketServer handler
                    Func <string, MessageReqPacket, ValueTask> writeMessageReqPacketHandler = WriteMessageReqPacketAsync;
                    Action <PushRespPacket> setPushRespPacketHandler     = SetPushRespPacket;
                    Action <IChannel, bool> channelActiveInActiveHandler = ActiveInActiveHandler;

                    pipeline.AddLast("SocketServerHandler", _app.ServiceProvider.CreateInstance <SocketServerHandler>(writeMessageReqPacketHandler, setPushRespPacketHandler, channelActiveInActiveHandler));
                }));

                _boundChannel = await bootstrap.BindAsync(_setting.ListeningEndPoint);

                _isRunning = true;

                _logger.LogInformation($"Socket server run! ListeningEndPoint:{_setting.ListeningEndPoint}, ChannelId:{_boundChannel.Id.AsLongText()}");

                StartScanTimeoutRequestTask();
                StartHandleMessageReqPacketTask();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Socket server run fail,ex:{0}.", ex.Message);
                await Task.WhenAll(
                    _bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(_setting.QuietPeriodMilliSeconds), TimeSpan.FromSeconds(_setting.CloseTimeoutSeconds)),
                    _workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(_setting.QuietPeriodMilliSeconds), TimeSpan.FromSeconds(_setting.CloseTimeoutSeconds)));
            }
        }
        Func <IPAddress, int, Task <IChannel> > CreateChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings)
        {
#if WINDOWS_UWP
            return(async(address, port) =>
            {
                PlatformProvider.Platform = new UWPPlatform();

                var eventLoopGroup = new MultithreadEventLoopGroup();

                var streamSocket = new StreamSocket();
                await streamSocket.ConnectAsync(new HostName(iotHubConnectionString.HostName), port.ToString(), SocketProtectionLevel.PlainSocket);

                streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                await streamSocket.UpgradeToSslAsync(SocketProtectionLevel.Tls12, new HostName(iotHubConnectionString.HostName));

                var streamSocketChannel = new StreamSocketChannel(streamSocket);

                streamSocketChannel.Pipeline.AddLast(
                    MqttEncoder.Instance,
                    new MqttDecoder(false, MaxMessageSize),
                    this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings));

                streamSocketChannel.Configuration.SetOption(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default);

                await eventLoopGroup.GetNext().RegisterAsync(streamSocketChannel);

                this.ScheduleCleanup(() =>
                {
                    EventLoopGroupPool.Release(this.eventLoopGroupKey);
                    return TaskConstants.Completed;
                });

                return streamSocketChannel;
            });
#else
            return((address, port) =>
            {
                IEventLoopGroup eventLoopGroup = EventLoopGroupPool.TakeOrAdd(this.eventLoopGroupKey);

                Func <Stream, SslStream> streamFactory = stream => new SslStream(stream, true, settings.RemoteCertificateValidationCallback);
                var clientTlsSettings = settings.ClientCertificate != null ?
                                        new ClientTlsSettings(iotHubConnectionString.HostName, new List <X509Certificate> {
                    settings.ClientCertificate
                }) :
                                        new ClientTlsSettings(iotHubConnectionString.HostName);
                Bootstrap bootstrap = new Bootstrap()
                                      .Group(eventLoopGroup)
                                      .Channel <TcpSocketChannel>()
                                      .Option(ChannelOption.TcpNodelay, true)
                                      .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                                      .Handler(new ActionChannelInitializer <ISocketChannel>(ch =>
                {
                    var tlsHandler = new TlsHandler(streamFactory, clientTlsSettings);

                    ch.Pipeline
                    .AddLast(
                        tlsHandler,
                        MqttEncoder.Instance,
                        new MqttDecoder(false, MaxMessageSize),
                        this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings));
                }));

                this.ScheduleCleanup(() =>
                {
                    EventLoopGroupPool.Release(this.eventLoopGroupKey);
                    return TaskConstants.Completed;
                });

                return bootstrap.ConnectAsync(address, port);
            });
#endif
        }
        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);
        }
 protected override IEventLoopGroup NewWorkerGroup(IEventLoopGroup serverGroup) => new MultithreadEventLoopGroup(1);
Example #35
0
        TaskCompletionSource <ConnectResult> connectFuture; //create a Task start with Connect, end by ConnAct.
        public async Task <ConnectResult> ConnectAsync(string host, int port)
        {
            if (isConnected())
            {
                return(new ConnectResult(true, ConnectReturnCode.Accepted, channel.CloseCompletion));
            }

            if (eventLoopGroup == null)
            {
                eventLoopGroup = new MultithreadEventLoopGroup();
            }

            connectFuture = new TaskCompletionSource <ConnectResult>();

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (ClientSettings.IsSsl)
            {
                cert       = new X509Certificate2(Path.Combine(ClientSettings.ProcessDirectory, ClientSettings.KeyFile), ClientSettings.Password);
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }
            var bootstrap = new Bootstrap();

            bootstrap
            .Group(eventLoopGroup)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .Handler(new ActionChannelInitializer <ISocketChannel>(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)));
                }
                if (ClientSettings.EnableLoggingHandler)
                {
                    pipeline.AddLast(new LoggingHandler());
                }
                pipeline.AddLast(MqttEncoder.Instance);
                pipeline.AddLast(new MqttDecoder(false, ClientSettings.MaxMessageSize));
                AddHandlers(pipeline);
                pipeline.AddLast(new MqttHandler(this));
            }));
            try
            {
                IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(host), port));

                if (clientChannel.Open)
                {
                    channel = clientChannel;
                    _       = clientChannel.CloseCompletion.ContinueWith((t, s) =>
                    {
                        var self = (MqttClient)s;
                        if (self.isConnected())
                        {
                            return;
                        }
                        if (self.OnConnectionChange != null)
                        {
                            if (connectFuture.Task.IsCompleted)
                            {
                                var result = connectFuture.Task.Result;
                                if (result.ReturnCode != ConnectReturnCode.Accepted)
                                {
                                    ChannelClosedException e = new ChannelClosedException(result.ReturnCode.ToString());
                                    self.OnConnectionChange.OnConnectionLost(e);
                                    connectFuture.TrySetException(e);
                                }//ConnAct with refused code.
                            }
                            else
                            {
                                ChannelClosedException e = new ChannelClosedException("Channel is closed!", connectFuture.Task.Exception);
                                self.OnConnectionChange.OnConnectionLost(e);
                                connectFuture.TrySetException(e);
                            }//Channel closed before ConnAct.
                        }
                        pendingPublishes.Clear();
                        pendingIncomingQoS2Publishes.Clear();
                        pendingSubscribes.Clear();
                        pendingSubscribeTopics.Clear();
                        pendingUnsubscribes.Clear();
                        topicSubscriptions.Clear();
                        subscribedTopics.Clear();
                        callbackSubscriptions.Clear();
                        reconnecting = true;
                        scheduleReconnect(host, port);//auto reconnect when channel closed.
                    }, this, TaskContinuationOptions.ExecuteSynchronously);
                }
                else
                {
                    var e = new ClosedChannelException();
                    if (OnConnectionChange != null)
                    {
                        OnConnectionChange.OnConnectionLost(e);
                    }
                    connectFuture.SetException(e);
                    scheduleReconnect(host, port);//auto reconnect when connect failed.
                }
            }
            catch (Exception e)
            {
                connectFuture.SetException(e);
                scheduleReconnect(host, port); //auto reconnect when connect error.
            }
            return(await connectFuture.Task);
        }
Example #36
0
 public DefaultEventLoop(IEventLoopGroup parent)
     : this(parent, DefaultMaxPendingTasks)
 {
 }
 public LoopExecutor(IEventLoopGroup parent, string threadName)
     : this(parent, threadName, DefaultBreakoutInterval)
 {
 }
Example #38
0
 public DefaultEventLoop(IEventLoopGroup parent, IRejectedExecutionHandler rejectedHandler)
     : this(parent, rejectedHandler, queueFactory : null)
 {
 }
Example #39
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmppConnection"/> class.
        /// </summary>
        /// <param name="pipelineInitializerAction">The pipeline initializer action.</param>
        /// <param name="eventLoopGroup">The event loop group.</param>
        protected XmppConnection(Action <IChannelPipeline> pipelineInitializerAction, IEventLoopGroup eventLoopGroup)
        {
            Contract.Requires <ArgumentNullException>(eventLoopGroup != null, $"{nameof(eventLoopGroup)} cannot be null");

            this.eventLoopGroup = eventLoopGroup;

            Bootstrap
            .Group(eventLoopGroup)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .Option(ChannelOption.SoKeepalive, true)
            .Resolver(HostnameResolver)
            .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
            .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                Pipeline = channel.Pipeline;

                Pipeline.AddLast2(new ZlibDecoder());
                Pipeline.AddLast2(new KeepAliveHandler());
                Pipeline.AddLast2(new XmlStreamDecoder());

                Pipeline.AddLast2(new ZlibEncoder());
                Pipeline.AddLast2(new XmppXElementEncoder());
                Pipeline.AddLast2(new UTF8StringEncoder());

                Pipeline.AddLast2(xmppStreamEventHandler);
                Pipeline.AddLast2(new StreamFooterHandler());
                Pipeline.AddLast2(XmppStanzaHandler);
                Pipeline.AddLast2(new CatchAllXmppStanzaHandler());
                Pipeline.AddLast2(new DisconnectHandler(this));

                pipelineInitializerAction?.Invoke(Pipeline);
            }));
        }
Example #40
0
 public DefaultEventLoop(IEventLoopGroup parent, IRejectedExecutionHandler rejectedHandler, IEventLoopTaskQueueFactory queueFactory)
     : this(parent, DefaultThreadFactory <DefaultEventLoop> .Instance, rejectedHandler, queueFactory)
 {
 }
Example #41
0
        ServerBootstrap SetupServerBootstrap()
        {
            int maxInboundMessageSize = this.settingsProvider.GetIntegerSetting("MaxInboundMessageSize", DefaultMaxInboundMessageSize);
            int threadCount           = this.settingsProvider.GetIntegerSetting("ThreadCount", this.defaultThreadCount);
            int listenBacklogSize     = this.settingsProvider.GetIntegerSetting("ListenBacklogSize", DefaultListenBacklogSize);
            int parentEventLoopCount  = this.settingsProvider.GetIntegerSetting("EventLoopCount", DefaultParentEventLoopCount);
            var settings = new Settings(this.settingsProvider);

            MessagingBridgeFactoryFunc bridgeFactory = this.mqttConnectionProvider.Connect;

            var bootstrap = new ServerBootstrap();
            // multithreaded event loop that handles the incoming connection
            IEventLoopGroup parentEventLoopGroup = new MultithreadEventLoopGroup(parentEventLoopCount);

            // multithreaded event loop (worker) that handles the traffic of the accepted connections
            this.eventLoopGroup = new MultithreadEventLoopGroup(threadCount);

            bootstrap.Group(parentEventLoopGroup, this.eventLoopGroup)
            .Option(ChannelOption.SoBacklog, listenBacklogSize)
            // Allow listening socket to force bind to port if previous socket is still in TIME_WAIT
            // Fixes "address is already in use" errors
            .Option(ChannelOption.SoReuseaddr, true)
            .ChildOption(ChannelOption.Allocator, this.byteBufferAllocator)
            .ChildOption(ChannelOption.AutoRead, AutoRead)
            // channel that accepts incoming connections
            .Channel <TcpServerSocketChannel>()
            // Channel initializer, it is handler that is purposed to help configure a new channel
            .ChildHandler(
                new ActionChannelInitializer <ISocketChannel>(
                    channel =>
            {
                var identityProvider = new DeviceIdentityProvider(this.authenticator, this.usernameParser, this.clientCredentialsFactory, this.metadataStore, this.clientCertAuthAllowed);

                // configure the channel pipeline of the new Channel by adding handlers
                TlsSettings serverSettings = new ServerTlsSettings(
                    certificate: this.tlsCertificate,
                    negotiateClientCertificate: this.clientCertAuthAllowed,
                    checkCertificateRevocation: false,
                    enabledProtocols: this.sslProtocols);

                channel.Pipeline.AddLast(
                    new TlsHandler(
                        stream =>
                        new SslStream(
                            stream,
                            true,
                            (sender, remoteCertificate, remoteChain, sslPolicyErrors) => this.RemoteCertificateValidationCallback(identityProvider, remoteCertificate, remoteChain)),
                        serverSettings));

                channel.Pipeline.AddLast(
                    MqttEncoder.Instance,
                    new MqttDecoder(true, maxInboundMessageSize),
                    new MqttAdapter(
                        settings,
                        this.sessionProvider,
                        identityProvider,
                        null,
                        bridgeFactory));
            }));

            var mqttWebSocketListener = new MqttWebSocketListener(
                settings,
                bridgeFactory,
                this.authenticator,
                this.usernameParser,
                this.clientCredentialsFactory,
                () => this.sessionProvider,
                new MultithreadEventLoopGroup(Environment.ProcessorCount),
                this.byteBufferAllocator,
                AutoRead,
                maxInboundMessageSize,
                this.clientCertAuthAllowed,
                this.metadataStore);

            this.webSocketListenerRegistry.TryRegister(mqttWebSocketListener);

            return(bootstrap);
        }
Example #42
0
 public DefaultEventLoop(IEventLoopGroup parent, IThreadFactory threadFactory, IEventLoopTaskQueueFactory queueFactory)
     : this(parent, threadFactory, RejectedExecutionHandlers.Reject(), queueFactory)
 {
 }
Example #43
0
 public SimpleChannelInboundHandler0(IEventLoopGroup group, CountdownEvent latch, bool sameEventLoop)
 {
     _group         = group;
     _latch         = latch;
     _sameEventLoop = sameEventLoop;
 }
 public StableTelemetryRunner(IEventLoopGroup eventLoopGroup, string deviceKey, string iotHubConnectionString, IPEndPoint endpoint, string tlsHostName)
     : base(eventLoopGroup, deviceKey, iotHubConnectionString, endpoint, tlsHostName)
 {
 }
 /// <summary>
 /// 创建 UDP 协议封装器。
 /// </summary>
 /// <param name="factory">给定的 <see cref="IBootstrapWrapperFactory"/>。</param>
 /// <param name="group">输出 <see cref="IEventLoopGroup"/>。</param>
 /// <returns>返回 <see cref="IBootstrapWrapper"/>。</returns>
 public static IBootstrapWrapper CreateUdp(this IBootstrapWrapperFactory factory, out IEventLoopGroup group)
 => factory.NotNull(nameof(factory))
 .Create(false, out group)
 .Configure(bootstrap => bootstrap.Channel <SocketDatagramChannel>());