From 14eb202873630be45dbbe90bd0775328e6b3aefb Mon Sep 17 00:00:00 2001 From: Christian <6939810+chkr1011@users.noreply.github.com> Date: Sat, 18 Jun 2022 11:38:36 +0200 Subject: [PATCH] Add new samples. --- Samples/Client/Client_Connection_Samples.cs | 62 ++++++++++++++-- Samples/Program.cs | 12 ++- Samples/Server/Server_Simple_Samples.cs | 81 ++++++++++++++++----- 3 files changed, 128 insertions(+), 27 deletions(-) diff --git a/Samples/Client/Client_Connection_Samples.cs b/Samples/Client/Client_Connection_Samples.cs index 97cb4668..4f6149a3 100644 --- a/Samples/Client/Client_Connection_Samples.cs +++ b/Samples/Client/Client_Connection_Samples.cs @@ -111,13 +111,21 @@ public static class Client_Connection_Samples .WithTls( o => { + // The used public broker sometimes has invalid certificates. This sample accepts all + // certificates. This should not be used in live environments. + o.CertificateValidationHandler = _ => true; + + // The default value is determined by the OS. Set manually to force version. o.SslProtocol = SslProtocols.Tls12; }) .Build(); - await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None); + using (var timeout = new CancellationTokenSource(5000)) + { + await mqttClient.ConnectAsync(mqttClientOptions, timeout.Token); - Console.WriteLine("The MQTT client is connected."); + Console.WriteLine("The MQTT client is connected."); + } } } @@ -159,19 +167,59 @@ public static class Client_Connection_Samples .WithTls( o => { - o.SslProtocol = SslProtocols.Tls12; // The default value is determined by the OS. Set manually to force version. + // The used public broker sometimes has invalid certificates. This sample accepts all + // certificates. This should not be used in live environments. + o.CertificateValidationHandler = _ => true; }) .Build(); // In MQTTv5 the response contains much more information. - var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None); + using (var timeout = new CancellationTokenSource(5000)) + { + var response = await mqttClient.ConnectAsync(mqttClientOptions, timeout.Token); + + Console.WriteLine("The MQTT client is connected."); - Console.WriteLine("The MQTT client is connected."); - - response.DumpToConsole(); + response.DumpToConsole(); + } } } + public static async Task Inspect_Certificate_Validation_Errors() + { + /* + * This sample prints the certificate information while connection. This data can be used to decide whether a connection is secure or not + * including the reason for that status. + */ + + var mqttFactory = new MqttFactory(); + + using (var mqttClient = mqttFactory.CreateMqttClient()) + { + var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("mqtt.fluux.io", 8883) + .WithTls( + o => + { + o.CertificateValidationHandler = eventArgs => + { + eventArgs.Certificate.Subject.DumpToConsole(); + eventArgs.Certificate.GetExpirationDateString().DumpToConsole(); + eventArgs.Chain.ChainPolicy.RevocationMode.DumpToConsole(); + eventArgs.Chain.ChainStatus.DumpToConsole(); + eventArgs.SslPolicyErrors.DumpToConsole(); + return true; + }; + }) + .Build(); + + // In MQTTv5 the response contains much more information. + using (var timeout = new CancellationTokenSource(5000)) + { + await mqttClient.ConnectAsync(mqttClientOptions, timeout.Token); + } + } + } + public static async Task Ping_Server() { /* diff --git a/Samples/Program.cs b/Samples/Program.cs index fdfe0e56..78f5b255 100644 --- a/Samples/Program.cs +++ b/Samples/Program.cs @@ -39,10 +39,16 @@ Console.WriteLine(); try { - var task = selectedSampleMethod.Invoke(null, null) as Task; - task?.Wait(); + if (selectedSampleMethod.Invoke(null, null) is Task task) + { + await task; + } } catch (Exception exception) { Console.WriteLine(exception.ToString()); -} \ No newline at end of file +} + +Console.WriteLine(); +Console.WriteLine("Press Enter to exit."); +Console.ReadLine(); \ No newline at end of file diff --git a/Samples/Server/Server_Simple_Samples.cs b/Samples/Server/Server_Simple_Samples.cs index 4017c5aa..02eea192 100644 --- a/Samples/Server/Server_Simple_Samples.cs +++ b/Samples/Server/Server_Simple_Samples.cs @@ -9,27 +9,66 @@ namespace MQTTnet.Samples.Server; public static class Server_Simple_Samples { + public static async Task Force_Disconnecting_Client() + { + /* + * This sample will disconnect a client. + * + * See _Run_Minimal_Server_ for more information. + */ + + using (var mqttServer = await StartMqttServer()) + { + // Let the client connect. + await Task.Delay(TimeSpan.FromSeconds(5)); + + // Now disconnect the client (if connected). + var affectedClient = (await mqttServer.GetClientsAsync()).FirstOrDefault(c => c.Id == "MyClient"); + if (affectedClient != null) + { + await affectedClient.DisconnectAsync(); + } + } + } + + public static async Task Publish_Message_From_Broker() + { + /* + * This sample will publish a message directly at the broker. + * + * See _Run_Minimal_Server_ for more information. + */ + + using (var mqttServer = await StartMqttServer()) + { + // Create a new message using the builder as usual. + var message = new MqttApplicationMessageBuilder().WithTopic("HelloWorld").WithPayload("Test").Build(); + + // Now inject the new message at the broker. + await mqttServer.InjectApplicationMessage( + new InjectedMqttApplicationMessage(message) + { + SenderClientId = "SenderClientId" + }); + } + } + 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(); - + 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(); - + new MqttServerOptionsBuilder().WithDefaultEndpoint().WithDefaultEndpointPort(1234).Build(); + using (var mqttServer = mqttFactory.CreateMqttServer(mqttServerOptions)) { await mqttServer.StartAsync(); @@ -50,13 +89,7 @@ public static class Server_Simple_Samples * See _Run_Minimal_Server_ for more information. */ - var mqttFactory = new MqttFactory(); - - var mqttServerOptions = new MqttServerOptionsBuilder() - .WithDefaultEndpoint() - .Build(); - - using (var mqttServer = mqttFactory.CreateMqttServer(mqttServerOptions)) + using (var mqttServer = await StartMqttServer()) { // Setup connection validation before starting the server so that there is // no change to connect without valid credentials. @@ -88,4 +121,18 @@ public static class Server_Simple_Samples await mqttServer.StopAsync(); } } + + static async Task 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; + } } \ No newline at end of file