Recently, I was evaluating few .NET C# MQTT Client Libraries. After a bit of research, I found the following interesting .NET C# MQTT Client Libraries:

After evaluating these, I found MQTTnet was the one which covers all my use cases. In this article, I will share how we can use MQTTnet .NET C# MQTT Client Library to publish & subscribe messages to MQTT Broker. I will be using CloudMQTT MQTT Broker Free Instance do this article.

Add “MQTTnet.Extensions.ManagedClient” Nuget package

Benefits of using Managed Client

Auto reconnect

Internal queuing support

Storage support that enables sending the messages even after application restart

No need to subscribe manually after disconnection from the server

Connect to the MQTT Broker (CloudMQTT)

/// <summary> /// Connect to broker. /// </summary> /// <returns>Task.</returns> public static async Task ConnectAsync() { string clientId = Guid.NewGuid().ToString(); string mqttURI = {REPLACE THIS WITH YOUR MQTT SERVER URI HERE} string mqttUser = { REPLACE THIS WITH YOUR MQTT USER HERE } string mqttPassword = { REPLACE THIS WITH YOUR MQTT PASSWORD HERE } int mqttPort = { REPLACE THIS WITH YOUR MQTT PORT HERE } bool mqttSecure = {IF YOU ARE USING SSL Port THEN SET true OTHERWISE SET false} var messageBuilder = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithCredentials(mqttUser, mqttPassword) .WithTcpServer(mqttURI, mqttPort) .WithCleanSession(); var options = mqttSecure ? messageBuilder .WithTls() .Build() : messageBuilder .Build(); var managedOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(options) .Build(); client = new MqttFactory().CreateManagedMqttClient(); await client.StartAsync(managedOptions); }

Setup CloudMQTT Broker Instance & get the instance info required for connection

Create New Instance

Select a plan and name

Select a region and data center

Confirm new instance

Select the newly created instance

Get the Broker Instance Info

Publish messages to the MQTT Broker (CloudMQTT)

/// <summary> /// Publish Message. /// </summary> /// <param name="topic">Topic.</param> /// <param name="payload">Payload.</param> /// <param name="retainFlag">Retain flag.</param> /// <param name="qos">Quality of Service.</param> /// <returns>Task.</returns> public static async Task PublishAsync(string topic, string payload, bool retainFlag = true, int qos = 1) => await client.PublishAsync(new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(payload) .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos) .WithRetainFlag(retainFlag) .Build());

Here, Quality of Service (QoS) can be

At most once (0)

At least once (1)

Exactly once (2)

Retain Message Flag can be true/false

While publishing, we can tell the MQTT broker to keep the last message on that topic by setting the retained message flag to true.

Subscribe messages from the MQTT Broker (CloudMQTT)

/// <summary> /// Subscribe topic. /// </summary> /// <param name="topic">Topic.</param> /// <param name="qos">Quality of Service.</param> /// <returns>Task.</returns> public static async Task SubscribeAsync(string topic, int qos = 1) => await client.SubscribeAsync(new TopicFilterBuilder() .WithTopic(topic) .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos) .Build());

Handle Events

Connected Handler

client.UseConnectedHandler(e => { Console.WriteLine("Connected successfully with MQTT Brokers."); });

Disconnected Handler

client.UseDisconnectedHandler(e => { Console.WriteLine("Disconnected from MQTT Brokers."); });

Message Received Handler

You can use this for processing the subscribed messages.

client.UseApplicationMessageReceivedHandler(e => { try { string topic = e.ApplicationMessage.Topic; if (string.IsNullOrWhiteSpace(topic) == false) { string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); Console.WriteLine($"Topic: {topic}. Message Received: {payload}"); } } catch (Exception ex) { Console.WriteLine(ex.Message, ex); } });

Check Published messages on MQTT Broker (CloudMQTT)

That’s ALL !!!