public static void RunEmptyServerWithLogging() { var logger = new MqttNetEventLogger(); MqttNetConsoleLogger.ForwardToConsole(logger); var mqttFactory = new MqttFactory(logger); var mqttServer = mqttFactory.CreateMqttServer(); mqttServer.StartAsync(new MqttServerOptions()).GetAwaiter().GetResult(); Console.WriteLine("Press any key to exit."); Console.ReadLine(); }
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 RunAsync() { try { var logger = new MqttNetLogger(); MqttNetConsoleLogger.ForwardToConsole(logger); var factory = new MqttFactory(logger); var client = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithTcpServer("localhost") .Build(); Console.WriteLine("BEFORE CONNECT"); await client.ConnectAsync(options); Console.WriteLine("AFTER CONNECT"); Console.WriteLine("BEFORE SUBSCRIBE"); await client.SubscribeAsync("test/topic"); Console.WriteLine("AFTER SUBSCRIBE"); Console.WriteLine("BEFORE PUBLISH"); await client.PublishAsync("test/topic", "payload"); Console.WriteLine("AFTER PUBLISH"); await Task.Delay(1000); Console.WriteLine("BEFORE DISCONNECT"); await client.DisconnectAsync(); Console.WriteLine("AFTER DISCONNECT"); Console.WriteLine("FINISHED"); } catch (Exception ex) { Console.WriteLine(ex); } }
public static async Task RunAsync() { try { var options = new MqttServerOptions { ConnectionValidator = new MqttServerConnectionValidatorDelegate(p => { if (p.ClientId == "SpecialClient") { if (p.Username != "USER" || p.Password != "PASS") { p.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword; } } }), Storage = new RetainedMessageHandler(), ApplicationMessageInterceptor = new MqttServerApplicationMessageInterceptorDelegate(context => { if (MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, "/myTopic/WithTimestamp/#")) { // Replace the payload with the timestamp. But also extending a JSON // based payload with the timestamp is a suitable use case. context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O")); } if (context.ApplicationMessage.Topic == "not_allowed_topic") { context.AcceptPublish = false; context.CloseConnection = true; } }), SubscriptionInterceptor = new MqttServerSubscriptionInterceptorDelegate(context => { if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin") { context.AcceptSubscription = false; } if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator") { context.AcceptSubscription = false; context.CloseConnection = true; } }) }; // Extend the timestamp for all messages from clients. // Protect several topics from being subscribed from every client. //var certificate = new X509Certificate(@"C:\certs\test\test.cer", ""); //options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert); //options.ConnectionBacklog = 5; //options.DefaultEndpointOptions.IsEnabled = true; //options.TlsEndpointOptions.IsEnabled = false; var mqttServer = new MqttFactory().CreateMqttServer(); mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e => { MqttNetConsoleLogger.PrintToConsole( $"'{e.ClientId}' reported '{e.ApplicationMessage.Topic}' > '{Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? new byte[0])}'", ConsoleColor.Magenta); }); //options.ApplicationMessageInterceptor = c => //{ // if (c.ApplicationMessage.Payload == null || c.ApplicationMessage.Payload.Length == 0) // { // return; // } // try // { // var content = JObject.Parse(Encoding.UTF8.GetString(c.ApplicationMessage.Payload)); // var timestampProperty = content.Property("timestamp"); // if (timestampProperty != null && timestampProperty.Value.Type == JTokenType.Null) // { // timestampProperty.Value = DateTime.Now.ToString("O"); // c.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(content.ToString()); // } // } // catch (Exception) // { // } //}; mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(e => { Console.Write("Client disconnected event fired."); }); await mqttServer.StartAsync(options); Console.WriteLine("Press any key to exit."); Console.ReadLine(); await mqttServer.StopAsync(); } catch (Exception e) { Console.WriteLine(e); } Console.ReadLine(); }
public static async Task RunAsync() { try { MqttNetConsoleLogger.ForwardToConsole(); var factory = new MqttFactory(); var client = factory.CreateMqttClient(); var clientOptions = new MqttClientOptions { ChannelOptions = new MqttClientTcpOptions { Server = "172.104.35.200" } }; client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e => { Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###"); Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}"); Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}"); Console.WriteLine(); }); client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(async e => { Console.WriteLine("### CONNECTED WITH SERVER ###"); await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build()); Console.WriteLine("### SUBSCRIBED ###"); }); client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async e => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await client.ConnectAsync(clientOptions); } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }); try { await client.ConnectAsync(clientOptions); } catch (Exception exception) { Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception); } Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###"); while (true) { Console.ReadLine(); await client.SubscribeAsync(new TopicFilter { Topic = "test", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce }); var applicationMessage = new MqttApplicationMessageBuilder() .WithTopic("A/B/C") .WithPayload("Hello World") .WithAtLeastOnceQoS() .Build(); await client.PublishAsync(applicationMessage); } } catch (Exception exception) { Console.WriteLine(exception); } }
public static async Task RunAsync() { try { MqttNetConsoleLogger.ForwardToConsole(); var options = new MqttServerOptions { ConnectionValidator = p => { if (p.ClientId == "SpecialClient") { if (p.Username != "USER" || p.Password != "PASS") { return(MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword); } } return(MqttConnectReturnCode.ConnectionAccepted); }, Storage = new RetainedMessageHandler(), ApplicationMessageInterceptor = context => { if (MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, "/myTopic/WithTimestamp/#")) { // Replace the payload with the timestamp. But also extending a JSON // based payload with the timestamp is a suitable use case. context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O")); } }, SubscriptionInterceptor = context => { if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin") { context.AcceptSubscription = false; } if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator") { context.AcceptSubscription = false; context.CloseConnection = true; } } }; // Extend the timestamp for all messages from clients. // Protect several topics from being subscribed from every client. //var certificate = new X509Certificate(@"C:\certs\test\test.cer", ""); //options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert); //options.ConnectionBacklog = 5; //options.DefaultEndpointOptions.IsEnabled = true; //options.TlsEndpointOptions.IsEnabled = false; var mqttServer = new MqttFactory().CreateMqttServer(); mqttServer.ClientDisconnected += (s, e) => { Console.Write("Client disconnected event fired."); }; await mqttServer.StartAsync(options); Console.WriteLine("Press any key to exit."); Console.ReadLine(); await mqttServer.StopAsync(); } catch (Exception e) { Console.WriteLine(e); } Console.ReadLine(); }