Пример #1
0
        public void Start()
        {
            _storageService.TryReadOrCreate(out MqttServiceOptions options, MqttServiceOptions.Filename);

            var mqttFactory = new MqttFactory();

            _enableMqttLogging = options.EnableLogging;
            if (_enableMqttLogging)
            {
                _mqttServer = mqttFactory.CreateMqttServer(new LoggerAdapter(_logger));
            }
            else
            {
                _mqttServer = mqttFactory.CreateMqttServer();
            }

            _mqttServer.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => OnApplicationMessageReceived(e)));

            var serverOptions = new MqttServerOptionsBuilder()
                                .WithDefaultEndpointPort(options.ServerPort)
                                .WithPersistentSessions();

            if (options.PersistRetainedMessages)
            {
                var storage = new MqttServerStorage(_storageService, _logger);
                storage.Start();
                serverOptions.WithStorage(storage);
            }

            _mqttServer.StartAsync(serverOptions.Build()).GetAwaiter().GetResult();

            Task.Factory.StartNew(() => ProcessIncomingMqttMessages(_systemCancellationToken.Token), _systemCancellationToken.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }
Пример #2
0
        private async Task StartMqttServer()
        {
            MqttTcpChannel.CustomCertificateValidationCallback = RemoteValidation;
            var logger  = new MqttLogger(_logger);
            var factory = new MqttFactory();

            _mqttServer = factory.CreateMqttServer(new List <IMqttServerAdapter> {
                new MqttTcpServerAdapter(logger)
            }, logger);
            _mqttServer.Started            += Started;
            _mqttServer.ClientConnected    += ClientConnected;
            _mqttServer.ClientDisconnected += ClientDisconnected;

            await _mqttServer.StartAsync(_options);

            // wait for 5 seconds for server to be started
            for (var i = 0; i < 100; i++)
            {
                if (serverStarted)
                {
                    return;
                }
                await Task.Delay(50);
            }
            throw new Exception("Mqtt Server did not start?");
        }
        private async Task StartMqttServer()
        {
            var logger  = new MqttLogger(_logger);
            var factory = new MqttFactory();

            _mqttServer = factory.CreateMqttServer(new List <IMqttServerAdapter> {
                new MqttTcpServerAdapter(logger.CreateChildLogger())
            }, logger);
            _mqttServer.StartedHandler            = this;
            _mqttServer.ClientConnectedHandler    = this;
            _mqttServer.ClientDisconnectedHandler = this;

            await _mqttServer.StartAsync(_options);

            // wait for 5 seconds for server to be started
            for (var i = 0; i < 100; i++)
            {
                if (serverStarted)
                {
                    _logger.LogDebug($"Waited for {i * 50} milliseconds for server to be started");
                    return;
                }
                await Task.Delay(50);
            }
            throw new Exception("Mqtt Server did not start?");
        }
Пример #4
0
        private IMqttServerOptions Initialize(IConfiguration settings)
        {
            //if (mqttServer != null) throw new Exception($"{name} Duplicate start");

            var config = new MQTTConfig();

            settings.GetSection("MQTT").Bind(config);

            var factory = new MqttFactory();

            mqttServer = factory.CreateMqttServer();

            return(new MqttServerOptionsBuilder()
                   .WithConnectionBacklog(100)
                   .WithConnectionValidator(c => { if (c.Username != config.User)
                                                   {
                                                       return;
                                                   }
                                                   if (c.Password != config.Pass)
                                                   {
                                                       return;
                                                   }
                                                   c.ReasonCode = MqttConnectReasonCode.Success; })
                   .WithDefaultEndpointPort(config.Port).Build());
        }
Пример #5
0
        public void Setup()
        {
            TopicGenerator.Generate(NumPublishers, NumTopicsPerPublisher, out var topicsByPublisher, out var singleWildcardTopicsByPublisher, out var multiWildcardTopicsByPublisher);
            _topics = topicsByPublisher.Values.First();

            var serverOptions = new MqttServerOptionsBuilder().WithDefaultEndpoint().Build();

            var factory = new MqttFactory();

            _mqttServer = factory.CreateMqttServer(serverOptions);
            _mqttClient = factory.CreateMqttClient();

            _mqttServer.StartAsync().GetAwaiter().GetResult();

            var clientOptions = new MqttClientOptionsBuilder()
                                .WithTcpServer("localhost").Build();

            _mqttClient.ConnectAsync(clientOptions).GetAwaiter().GetResult();

            foreach (var topic in _topics)
            {
                var subscribeOptions = new MqttClientSubscribeOptionsBuilder()
                                       .WithTopicFilter(topic)
                                       .Build();
                _mqttClient.SubscribeAsync(subscribeOptions).GetAwaiter().GetResult();
            }
        }
Пример #6
0
        public async Task RunAsync()
        {
            if (bool.Parse(_configuration.GetSection("MQTT").GetSection("EnableDebugLogging").Value))
            {
                var mqttNetLogger = new MqttNetLoggerWrapper(_logger);
                _mqttFactory = new MqttFactory(mqttNetLogger);

                _logger.LogWarning("Debug logging is enabled. Performance of MQTTnet Server is decreased!");
            }
            else
            {
                _mqttFactory = new MqttFactory();
            }

            var server = _mqttFactory.CreateMqttServer();

            var serverOptions = new MqttServerOptionsBuilder()
                                .WithDefaultEndpointBoundIPAddress(IPAddress.Parse(_configuration.GetSection("MQTT").GetSection("IP").Value))
                                .WithDefaultEndpointBoundIPV6Address(IPAddress.None)
                                .WithDefaultEndpointPort(int.Parse(_configuration.GetSection("MQTT").GetSection("Port").Value))
                                .Build();

            server.ApplicationMessageReceivedHandler = _messageReceivedHandler;
            server.ClientConnectedHandler            = _clientConnectedHandler;
            server.ClientDisconnectedHandler         = _clientDisconnectedHandler;

            await server.StartAsync(serverOptions);
        }
Пример #7
0
        /// <summary>
        /// 6
        /// </summary>
        /// <returns></returns>
        static async Task ServerAndClientTestRunAsync()
        {
            MqttNetConsoleLogger.ForwardToConsole();

            var factory = new MqttFactory();

            var server = factory.CreateMqttServer();
            var client = factory.CreateMqttClient();


            var serverOptions = new MqttServerOptionsBuilder().Build();

            server.ApplicationMessageReceived += Server_ApplicationMessageReceived;
            await server.StartAsync(serverOptions);

            var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").Build();

            client.ApplicationMessageReceived += Client_ApplicationMessageReceived;


            await client.ConnectAsync(clientOptions);

            Task.Run(() =>
            {
                while (client.IsConnected)
                {
                    client.PublishAsync("test/topic", "hello").GetAwaiter().GetResult();
                    Thread.Sleep(500);
                }
            });

            client.SubscribeAsync("test/topic");
        }
Пример #8
0
        public void Setup()
        {
            var factory   = new MqttFactory();
            var tcpServer = new MqttTcpServerAdapter(new MqttNetEventLogger());

            tcpServer.ClientHandler += args =>
            {
                _serverChannel =
                    (IMqttChannel)args.GetType().GetField("_channel",
                                                          System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
                    .GetValue(args);

                return(Task.CompletedTask);
            };

            _mqttServer = factory.CreateMqttServer(new[] { tcpServer }, new MqttNetEventLogger());

            var serverOptions = new MqttServerOptionsBuilder().Build();

            _mqttServer.StartAsync(serverOptions).GetAwaiter().GetResult();

            var clientOptions = new MqttClientOptionsBuilder()
                                .WithTcpServer("localhost").Build();

            var tcpOptions = (MqttClientTcpOptions)clientOptions.ChannelOptions;

            _clientChannel = new MqttTcpChannel(new MqttClientOptions {
                ChannelOptions = tcpOptions
            });

            _clientChannel.ConnectAsync(CancellationToken.None).GetAwaiter().GetResult();
        }
        public async Task InitializeAsync()
        {
            var factory = new MqttFactory();

            MqttServer  = factory.CreateMqttServer();
            MqttClient1 = factory.CreateMqttClient();
            MqttClient2 = factory.CreateMqttClient();
            MqttClient1.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(args => Client1MessageReceived?.Invoke(this, args));
            MqttClient2.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(args => Client2MessageReceived?.Invoke(this, args));

            var brokerIpAddress = IPAddress.Loopback;
            var brokerPort      = 1885;

            var mqttServerOptions = new MqttServerOptionsBuilder()
                                    .WithClientId("broker")
                                    .WithDefaultEndpointBoundIPAddress(brokerIpAddress)
                                    .WithDefaultEndpointPort(brokerPort)
                                    .Build();
            var mqttClient1Options = new MqttClientOptionsBuilder()
                                     .WithClientId("client1")
                                     .WithTcpServer(brokerIpAddress.ToString(), brokerPort)
                                     .Build();
            var mqttClient2Options = new MqttClientOptionsBuilder()
                                     .WithClientId("client2")
                                     .WithTcpServer(brokerIpAddress.ToString(), brokerPort)
                                     .Build();

            await MqttServer.StartAsync(mqttServerOptions).ConfigureAwait(false);

            var connectClient1Result = await MqttClient1.ConnectAsync(mqttClient1Options).ConfigureAwait(false);

            var connectClient2Result = await MqttClient2.ConnectAsync(mqttClient2Options).ConfigureAwait(false);
        }
Пример #10
0
    public static async Task Run_Minimal_Server()
    {
        /*
         * This sample starts a simple MQTT server which will accept any TCP connection.
         */

        var mqttFactory = new MqttFactory();

        // The port for the default endpoint is 1883.
        // The default endpoint is NOT encrypted!
        // Use the builder classes where possible.
        var mqttServerOptions = new MqttServerOptionsBuilder().WithDefaultEndpoint().Build();

        // The port can be changed using the following API (not used in this example).
        // new MqttServerOptionsBuilder()
        //     .WithDefaultEndpoint()
        //     .WithDefaultEndpointPort(1234)
        //     .Build();

        using (var mqttServer = mqttFactory.CreateMqttServer(mqttServerOptions))
        {
            await mqttServer.StartAsync();

            Console.WriteLine("Press Enter to exit.");
            Console.ReadLine();

            // Stop and dispose the MQTT server if it is no longer needed!
            await mqttServer.StopAsync();
        }
    }
Пример #11
0
        public void Create_MqttServer()
        {
            var factory = new MqttFactory();
            var server  = factory.CreateMqttServer(new MqttServerOptionsBuilder().Build());

            Assert.IsNotNull(server);
        }
Пример #12
0
        public void Create_MqttServer()
        {
            var factory = new MqttFactory();
            var server  = factory.CreateMqttServer();

            Assert.IsNotNull(server);
        }
Пример #13
0
    public static async Task Run_Server_With_Logging()
    {
        /*
         * This sample starts a simple MQTT server and prints the logs to the output.
         *
         * IMPORTANT! Do not enable logging in live environment. It will decrease performance.
         *
         * See sample "Run_Minimal_Server" for more details.
         */

        var mqttFactory = new MqttFactory(new ConsoleLogger());

        var mqttServerOptions = new MqttServerOptionsBuilder().WithDefaultEndpoint().Build();

        using (var mqttServer = mqttFactory.CreateMqttServer(mqttServerOptions))
        {
            await mqttServer.StartAsync();

            Console.WriteLine("Press Enter to exit.");
            Console.ReadLine();

            // Stop and dispose the MQTT server if it is no longer needed!
            await mqttServer.StopAsync();
        }
    }
Пример #14
0
        public IMqttServer CreateMqttServer(List <IMqttServerAdapter> adapters)
        {
            if (adapters == null)
            {
                throw new ArgumentNullException(nameof(adapters));
            }

            return(_mqttFactory.CreateMqttServer(adapters));
        }
Пример #15
0
 public MqttServer(System.Net.IPAddress iPAddress, int port)
 {
     server  = factory.CreateMqttServer();
     options = new MqttServerOptionsBuilder()
               .WithDefaultEndpointBoundIPAddress(iPAddress)
               .WithDefaultEndpointPort(port)
               .WithApplicationMessageInterceptor(OnMessage)
               .Build();
 }
Пример #16
0
 public void InitialServer()
 {
     factory     = new MqttFactory();
     this.Server = factory.CreateMqttServer();
     Options     = new MqttServerOptionsBuilder()
                   .WithDefaultEndpointBoundIPAddress(IPAddress.Any)
                   .WithDefaultEndpointPort(23000)
                   .WithClientId("Server")
                   .WithConnectionBacklog(100);
 }
Пример #17
0
    static async Task <MqttServer> StartMqttServer()
    {
        var mqttFactory = new MqttFactory();

        // Due to security reasons the "default" endpoint (which is unencrypted) is not enabled by default!
        var mqttServerOptions = mqttFactory.CreateServerOptionsBuilder().WithDefaultEndpoint().Build();
        var server            = mqttFactory.CreateMqttServer(mqttServerOptions);
        await server.StartAsync();

        return(server);
    }
Пример #18
0
        public async Task <IMqttServer> StartServerAsync(MqttServerOptionsBuilder options)
        {
            if (Server != null)
            {
                throw new InvalidOperationException("Server already started.");
            }

            Server = new TestServerWrapper(_mqttFactory.CreateMqttServer(_serverLogger), TestContext, this);
            await Server.StartAsync(options.WithDefaultEndpointPort(ServerPort).Build());

            return(Server);
        }
Пример #19
0
        public void Start()
        {
            _storageService.TryReadOrCreate(out _options, DefaultDirectoryNames.Configuration, MqttServiceOptions.Filename);

            var mqttFactory = new MqttFactory();

            IsLowLevelMqttLoggingEnabled = _options.EnableLogging;
            if (IsLowLevelMqttLoggingEnabled)
            {
                _mqttServer = mqttFactory.CreateMqttServer(new LoggerAdapter(_logger));
            }
            else
            {
                _mqttServer = mqttFactory.CreateMqttServer();
            }

            _mqttServer.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => OnApplicationMessageReceived(e)));

            var serverOptions = new MqttServerOptionsBuilder()
                                .WithDefaultEndpointPort(_options.ServerPort)
                                .WithConnectionValidator(ValidateClientConnection)
                                .WithPersistentSessions();

            if (_options.PersistRetainedMessages)
            {
                var storage = new MqttServerStorage(_storageService, _logger);
                storage.Start();
                serverOptions.WithStorage(storage);
            }

            _mqttServer.StartAsync(serverOptions.Build()).GetAwaiter().GetResult();

            _workerThread = new Thread(ProcessIncomingMqttMessages)
            {
                Name         = nameof(MqttService),
                IsBackground = true
            };

            _workerThread.Start();
        }
Пример #20
0
        public void Start()
        {
            _storageService.TryReadOrCreate(out MqttServiceOptions options, MqttServiceOptions.Filename);

            var mqttFactory = new MqttFactory();

            IsLowLevelMqttLoggingEnabled = options.EnableLogging;
            if (IsLowLevelMqttLoggingEnabled)
            {
                _mqttServer = mqttFactory.CreateMqttServer(new LoggerAdapter(_logger));
            }
            else
            {
                _mqttServer = mqttFactory.CreateMqttServer();
            }

            _mqttServer.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => OnApplicationMessageReceived(e)));

            var serverOptions = new MqttServerOptionsBuilder()
                                .WithDefaultEndpointPort(options.ServerPort)
                                .WithPersistentSessions();

            if (options.PersistRetainedMessages)
            {
                var storage = new MqttServerStorage(_storageService, _logger);
                storage.Start();
                serverOptions.WithStorage(storage);
            }

            _mqttServer.StartAsync(serverOptions.Build()).GetAwaiter().GetResult();

            _workerThread = new Thread(ProcessIncomingMqttMessages)
            {
                Priority     = ThreadPriority.AboveNormal,
                IsBackground = true
            };

            _workerThread.Start();
        }
Пример #21
0
        protected override void OnStart()
        {
            _storageService.SafeReadSerializedValue(out _options, DefaultDirectoryNames.Configuration, MqttServiceOptions.Filename);

            IsLowLevelMqttLoggingEnabled = _options.EnableLogging;

            var mqttFactory = new MqttFactory();

            IMqttNetLogger mqttNetLogger;

            if (IsLowLevelMqttLoggingEnabled)
            {
                mqttNetLogger = new LoggerAdapter(_logger);
            }
            else
            {
                mqttNetLogger = new MqttNetLogger();
            }

            _webSocketServerAdapter = new MqttWebSocketServerAdapter(mqttNetLogger);

            var serverAdapters = new List <IMqttServerAdapter>
            {
                new MqttTcpServerAdapter(mqttNetLogger),
                _webSocketServerAdapter
            };

            _mqttServer = mqttFactory.CreateMqttServer(serverAdapters, mqttNetLogger);
            _mqttServer.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => OnApplicationMessageReceived(e)));

            var serverOptions = new MqttServerOptionsBuilder()
                                .WithDefaultEndpointPort(_options.ServerPort)
                                .WithConnectionValidator(ValidateClientConnection)
                                .WithPersistentSessions();

            if (_options.PersistRetainedMessages)
            {
                var storage = new MqttServerStorage(_storageService, _systemCancellationToken, _logger);
                storage.Start();
                serverOptions.WithStorage(storage);
            }

            _mqttServer.StartAsync(serverOptions.Build()).GetAwaiter().GetResult();

            _systemCancellationToken.Token.Register(() =>
            {
                _mqttServer.StopAsync().GetAwaiter().GetResult();
            });

            ParallelTask.StartLongRunning(ProcessIncomingMqttMessages, _systemCancellationToken.Token, _logger);
        }
Пример #22
0
        static async Task Main(string[] args)
        {
            var serverLogger = new MqttLoggerFactory().Create("Server");
            var clientLogger = new MqttLoggerFactory().Create("Client");

            IMqttFactory mqttFactory = new MqttFactory();

            //STARTING SERVER
            var mqttServer = mqttFactory.CreateMqttServer(serverLogger);
            await mqttServer.StartAsync(new MqttServerOptionsBuilder().Build());

            //STARTING CLIENT
            var mqttClient = mqttFactory.CreateMqttClient(clientLogger);

            var options = new MqttClientOptionsBuilder()
                          .WithClientId("Client1")
                          .WithTcpServer("localhost")
                          .WithCleanSession(false).Build();
            await mqttClient.ConnectAsync(options);

            await mqttClient.SubscribeAsync("testtopic/1", MqttQualityOfServiceLevel.AtLeastOnce);

            await mqttClient.SubscribeAsync("testtopic/2", MqttQualityOfServiceLevel.AtLeastOnce);

            mqttClient.UseApplicationMessageReceivedHandler(async e =>
            {
                if (e.ApplicationMessage.Topic == "testtopic/1")
                {
                    var messageMqtt2 = new MqttApplicationMessageBuilder()
                                       .WithTopic("testtopic/2")
                                       .WithPayload("Hello2")
                                       .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
                                       .WithRetainFlag(false)
                                       .Build();

                    await mqttClient.PublishAsync(messageMqtt2);
                }
            });

            var messageMqtt1 = new MqttApplicationMessageBuilder()
                               .WithTopic("testtopic/1")
                               .WithPayload("Hello1")
                               .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
                               .WithRetainFlag(false)
                               .Build();

            await mqttClient.PublishAsync(messageMqtt1);

            Console.WriteLine("Finish!");
            Console.ReadKey();
        }
Пример #23
0
        public static void RunEmptyServerWithLogging()
        {
            var logger = new MqttNetEventLogger();

            MqttNetConsoleLogger.ForwardToConsole(logger);

            var mqttFactory = new MqttFactory(logger);
            var mqttServer  = mqttFactory.CreateMqttServer(new MqttServerOptions());

            mqttServer.StartAsync().GetAwaiter().GetResult();

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
Пример #24
0
            /// <summary>
            /// IotService OnStart
            /// </summary>
            /// <param name="args"></param>
            protected override void OnStart(string[] args)
            {
                // todo: 引入记录服务的 nlogger file
                nlogger.Trace("IotService OnStart..");
                try
                {
                    // get local ip address
                    foreach (IPAddress _ipaddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                    {
                        if (_ipaddress.AddressFamily.ToString() == "InterNetwork")
                        {
                            nlogger.Debug("get the local ip address: " + _ipaddress.ToString());
                            mqttServerUrl = _ipaddress;
                        }
                    }

                    if (mqttServer == null)
                    {
                        nlogger.Trace("create new mqttServer. IP:" + mqttServerUrl.ToString() + " port:" + mqttPort.ToString());

                        var factory = new MqttFactory();
                        mqttServer = factory.CreateMqttServer() as MqttServer;

                        options = new MqttServerOptionsBuilder()
                                  .WithConnectionBacklog(1000)
                                  .WithDefaultEndpointPort(mqttPort)
                                  .WithDefaultEndpointBoundIPAddress(mqttServerUrl)
                                  .Build();

                        (options as MqttServerOptions).ConnectionValidator = new MqttServerConnectionValidatorDelegate(new Func <MqttConnectionValidatorContext, Task>(ConnectionValidation));

                        mqttServer.ClientConnectedHandler            = new MqttServerClientConnectedHandlerDelegate(new Func <MqttServerClientConnectedEventArgs, Task>(Connected));
                        mqttServer.ClientDisconnectedHandler         = new MqttServerClientDisconnectedHandlerDelegate(new Func <MqttServerClientDisconnectedEventArgs, Task>(DisConnected));
                        mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(new Action <MqttApplicationMessageReceivedEventArgs>(MqttApplicationMessageReceived));
                        mqttServer.ClientSubscribedTopicHandler      = new MqttServerClientSubscribedHandlerDelegate(new Func <MqttServerClientSubscribedTopicEventArgs, Task>(SubscribeTopic));
                        mqttServer.ClientUnsubscribedTopicHandler    = new MqttServerClientUnsubscribedTopicHandlerDelegate(new Func <MqttServerClientUnsubscribedTopicEventArgs, Task>(UnSubscribeTopic));
                        mqttServer.StartedHandler = new MqttServerStartedHandlerDelegate(new Action <EventArgs>(Started));
                        mqttServer.StoppedHandler = new MqttServerStoppedHandlerDelegate(new Action <EventArgs>(Stopped));
                    }

                    // 启动 Mqtt 服务
                    mqttServer.StartAsync(options);
                }
                catch (Exception ex)
                {
                    nlogger.Error("Exception occur in OnStart, stop this IotService.");
                    this.Stop();
                }
            }
Пример #25
0
        public async Task Setup()
        {
            new TopicGenerator().Generate(NumPublishers, NumTopicsPerPublisher, out _topicsByPublisher, out _singleWildcardTopicsByPublisher, out _multiWildcardTopicsByPublisher);

            var serverOptions = new MqttServerOptionsBuilder().WithDefaultEndpoint().Build();
            var factory       = new MqttFactory();

            _mqttServer = factory.CreateMqttServer(serverOptions);
            await _mqttServer.StartAsync();

            Console.WriteLine();
            Console.WriteLine("Begin connect " + NumPublishers + " publisher(s)...");

            var stopWatch = new System.Diagnostics.Stopwatch();

            stopWatch.Start();
            _mqttPublisherClientsByPublisherName = new Dictionary <string, IMqttClient>();
            foreach (var pt in _topicsByPublisher)
            {
                var publisherName    = pt.Key;
                var mqttClient       = factory.CreateMqttClient();
                var publisherOptions = new MqttClientOptionsBuilder()
                                       .WithTcpServer("localhost")
                                       .WithClientId(publisherName)
                                       .Build();
                await mqttClient.ConnectAsync(publisherOptions);

                _mqttPublisherClientsByPublisherName.Add(publisherName, mqttClient);
            }
            stopWatch.Stop();

            Console.Write($"{NumPublishers} publisher(s) connected in {stopWatch.ElapsedMilliseconds / 1000.0:0.000} seconds, ");
            Console.WriteLine($"connections per second: {NumPublishers / (stopWatch.ElapsedMilliseconds / 1000.0):0.000}");

            _mqttSubscriberClients = new List <IMqttClient>();
            for (var i = 0; i < NumSubscribers; ++i)
            {
                var mqttClient       = factory.CreateMqttClient();
                var subsriberOptions = new MqttClientOptionsBuilder()
                                       .WithTcpServer("localhost")
                                       .WithClientId("sub" + i)
                                       .Build();
                await mqttClient.ConnectAsync(subsriberOptions);

                mqttClient.ApplicationMessageReceivedAsync += HandleApplicationMessageReceivedAsync;
                _mqttSubscriberClients.Add(mqttClient);
            }
        }
Пример #26
0
        public static async Task RunAsync()
        {
            MqttNetConsoleLogger.ForwardToConsole();

            var factory = new MqttFactory();
            var server  = factory.CreateMqttServer();
            var client  = factory.CreateMqttClient();

            var serverOptions = new MqttServerOptionsBuilder().Build();
            await server.StartAsync(serverOptions);

            var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("localhost").Build();
            await client.ConnectAsync(clientOptions);

            await Task.Delay(Timeout.Infinite);
        }
    public static async Task Validating_Connections()
    {
        /*
         * This sample starts a simple MQTT server which will check for valid credentials and client ID.
         *
         * See _Run_Minimal_Server_ for more information.
         */

        var mqttFactory = new MqttFactory();

        var mqttServerOptions = new MqttServerOptionsBuilder()
                                .WithDefaultEndpoint()
                                .Build();

        using (var mqttServer = mqttFactory.CreateMqttServer(mqttServerOptions))
        {
            // Setup connection validation before starting the server so that there is
            // no change to connect without valid credentials.
            mqttServer.ValidatingConnectionAsync += e =>
            {
                if (e.ClientId != "ValidClientId")
                {
                    e.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                }

                if (e.Username != "ValidUser")
                {
                    e.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                }

                if (e.Password != "SecretPassword")
                {
                    e.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                }

                return(Task.CompletedTask);
            };

            await mqttServer.StartAsync();

            Console.WriteLine("Press Enter to exit.");
            Console.ReadLine();

            await mqttServer.StopAsync();
        }
    }
Пример #28
0
        public static async Task RunClientAndServer()
        {
            try
            {
                var mqttFactory       = new MqttFactory();
                var mqttServerOptions = new MqttServerOptionsBuilder().WithDefaultEndpoint().Build();
                var mqttServer        = mqttFactory.CreateMqttServer(mqttServerOptions);
                await mqttServer.StartAsync().ConfigureAwait(false);

                var options = new MqttClientOptions
                {
                    ChannelOptions = new MqttClientTcpOptions
                    {
                        Server = "127.0.0.1"
                    }
                };

                var client = mqttFactory.CreateMqttClient();
                await client.ConnectAsync(options).ConfigureAwait(false);

                var message = new MqttApplicationMessageBuilder().WithTopic("t")
                              .Build();

                var stopwatch = new Stopwatch();

                for (var i = 0; i < 10; i++)
                {
                    stopwatch.Restart();

                    var sentMessagesCount = 0;
                    while (stopwatch.ElapsedMilliseconds < 1000)
                    {
                        await client.PublishAsync(message, CancellationToken.None).ConfigureAwait(false);

                        sentMessagesCount++;
                    }

                    Console.WriteLine($"Sending {sentMessagesCount} messages per second. #" + (i + 1));
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Пример #29
0
        public async Task Publish_Special_Content()
        {
            var factory       = new MqttFactory();
            var server        = factory.CreateMqttServer();
            var serverOptions = new MqttServerOptionsBuilder().Build();

            var receivedMessages = new List <MqttApplicationMessage>();

            var client = factory.CreateMqttClient();

            try
            {
                await server.StartAsync(serverOptions);

                client.Connected += async(s, e) =>
                {
                    await client.SubscribeAsync("RCU/P1/H0001/R0003");

                    var msg = new MqttApplicationMessageBuilder()
                              .WithPayload("DA|18RS00SC00XI0000RV00R100R200R300R400L100L200L300L400Y100Y200AC0102031800BELK0000BM0000|")
                              .WithTopic("RCU/P1/H0001/R0003");

                    await client.PublishAsync(msg.Build());
                };

                client.ApplicationMessageReceived += (s, e) =>
                {
                    lock (receivedMessages)
                    {
                        receivedMessages.Add(e.ApplicationMessage);
                    }
                };

                await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build());

                await Task.Delay(500);

                Assert.AreEqual(1, receivedMessages.Count);
                Assert.AreEqual("DA|18RS00SC00XI0000RV00R100R200R300R400L100L200L300L400Y100Y200AC0102031800BELK0000BM0000|", receivedMessages.First().ConvertPayloadToString());
            }
            finally
            {
                await server.StopAsync();
            }
        }
Пример #30
0
        private async void StartMqttServer()
        {
            ClientDispatcher = Dispatcher.CurrentDispatcher;
            SetStatus("Configuring");
            MqttFactory factory = new MqttFactory();
            MqttServerOptionsBuilder optionsBuilder = new MqttServerOptionsBuilder()
                                                      .WithDefaultCommunicationTimeout(new TimeSpan(0, 0, 0, 60, 0))
                                                      .WithDefaultEndpoint()
                                                      .WithDefaultEndpointPort(PlainPort)
                                                      .WithMaxPendingMessagesPerClient(2000)
            ;

            Server = factory.CreateMqttServer();

            Server.ApplicationMessageReceived += Server_ApplicationMessageReceived;
            Server.ClientConnected            += Server_ClientConnected;
            Server.ClientDisconnected         += Server_ClientDisconnected;
            Server.ClientSubscribedTopic      += Server_ClientSubscribedTopic;
            Server.ClientUnsubscribedTopic    += Server_ClientUnsubscribedTopic;
            Server.Started += Server_Started;

#if HAVE_SYNC
            if (IsSync)
            {
                Server.Start(optionsBuilder.Build());
            }
            else
#endif
            await Server.StartAsync(optionsBuilder.Build());

            SetStatus("Started");
            // This will run the event queue forever, until we stop it
            Dispatcher.Run();

#if HAVE_SYNC
            if (IsSync)
            {
                Server.Stop();
            }
            else
#endif
            Server.StopAsync().Wait();

            await Dispatcher.BeginInvoke((Action)(() => OnServerThreadStopped()));
        }