Internet of Things (IoT): MQTT Publishing & Subscribing messages to MQTT Broker (CloudMQTT) using .NET C# MQTT Client Library
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 !!!
.NET Professional | Microsoft Certified Professional | DZone’s Most Valuable Blogger | Web Developer | Author | Blogger
Doctorate in Computer Science and Engineering
Microsoft Certified Professional (MCP) with over 12+ years of software industry experience including development, implementation & deployment of applications in the .NET framework
Experienced and skilled Agile Developer with a strong record of excellent teamwork, successful coding & project management. Specialises in problem identification and proposal of alternative solutions. Provided knowledge and individual mentoring to team members as needed
Among top 3% overall in terms of contribution on Stack Overflow (~2.3 million people reached my posts). Part of the top 1% Stack Overflow answerers in ASP.NET technology.
DZone’s Most Valuable Blogger (MVB)
Created and actively maintain the TechCartNow.com tech blog while also editing, writing, and researching topics for publication.
Excellent skills in Application Development using C#/Vb.Net, .NET Framework, ASP.NET, MVC, ADO.NET, WCF, WPF, Web API, SQL Server, jQuery, Angular, React, BackboneJS
When i am running this program its telling “Disconnected from MQTT Brokers.”
However i can publish from mosquitto_pub tool, any solution?
Can’t this be setted up as broker,Instead of connection to CloudMQTT broker.