DZone
IoT Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > IoT Zone > MQTT Publishing and Subscribing Messages to MQTT Broker (CloudMQTT) Using .NET C# MQTT Client Library

MQTT Publishing and Subscribing Messages to MQTT Broker (CloudMQTT) Using .NET C# MQTT Client Library

Learn more about MQTT publishing and subscribing with MQTT Broker using .NET C# Client Library.

Kapil Khandelwal user avatar by
Kapil Khandelwal
·
Aug. 14, 19 · IoT Zone · Tutorial
Like (4)
Save
Tweet
78.09K Views

Join the DZone community and get the full member experience.

Join For Free

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

  1. MqttDotNet
  2. paho.mqtt.m2mqtt
  3. MQTTnet

After evaluating these, I found MQTTnet was the one that covers all my use cases. In this article, I will share how we can use MQTTnet .NET C# MQTT Client Library to publish and subscribe messages to MQTT Broker. I will be using CloudMQTT MQTT Broker Free Instance for 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);
}


Set Up the CloudMQTT Broker Instance and 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 for now!

MQTT Library

Published at DZone with permission of Kapil Khandelwal, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Send Push Notifications to Users of Another App
  • Back to Basics: Accessing Kubernetes Pods
  • SRE: From Theory to Practice: What's Difficult About Incident Command?
  • How to Build Spark Lineage for Data Lakes

Comments

IoT Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo