Implementing MQTT in C#

by HiveMQ Team
9 min read

MQTT is a machine-to-machine communication protocol designed to enable efficient data exchange in IoT systems. Developers can use C# to implement MQTT and write applications for real-time communications using minimal resources. MQTT uses less code and data than other communication protocols and is a natural fit for IoT applications. Its publish/subscribe model means that when a user has subscribed to a topic, they will receive new data automatically when it is published to the broker without needing to regularly poll a server to check for new data. 

C# is an object-oriented programming language. It’s designed to be simple and general-purpose and supports applications written for both hosted and embedded systems. C# runs on .NET, a software framework developed by Microsoft. Developers can use a C# MQTT client to connect to an MQTT broker, publish data, and subscribe to topics to receive data.

In one of our previous blogs, How to Build .Net IoT Apps Using C# MQTT Client, we shared a detailed step-by-step process for building a .Net IoT application using the HiveMQ MQTT Client library for C# and HiveMQ Cloud Serverless. In this article, we will walk through how to connect a C# MQTT client using HiveMQ Self-Managed including HiveMQ Community Edition. 

How to Use an MQTT C# Client?

MQTT C# clients allow developers to write C# applications to connect to a broker, publish messages, and subscribe to topics. In this blog post we will be using HiveMQ C# MQTT client for .NET, which is open source and is compatible with all major MQTT brokers. It supports C# for .NET 6.0 and greater and its API is asynchronous. 

To get started with the HiveMQ C# MQTT client, first install the .NET environment.

The client is available on NuGet.org and you can install it with the following code.

dotnet add package HiveMQtt

Setting Up MQTT Broker for C# MQTT Client Connection

Next, you'll want to set up a client instance, and this requires configuring an MQTT broker. Though there's an option to connect your C# MQTT client to the fully managed HiveMQ Cloud Serverless service, the upcoming code is tailored for self-managed options: either the HiveMQ Enterprise or the open source Community edition.

Once you've downloaded the broker, configured security settings, and launched your chosen edition, make sure to note the hostname or IP address of your broker instance, as it will be required in the following code.

var options = new HiveMQClientOptions();
options.Host = 'hostname';
options.Port = 8883;
var client = new HiveMQClient(options);

How Do I Connect to an MQTT Broker in C#?

Once you’ve created a client instance, you can connect to an MQTT broker. The following code is an example of connecting with authentication credentials.

var options = new HiveMQClientOptions();
options.UserName = 'username';
options.Password = Environment.GetEnvironmentVariable("password");

var client = new HiveMQClient(options);
var connectResult = await client.ConnectAsync().ConfigureAwait(false);

After you’ve connected to a broker, you can publish messages and subscribe to topics to share data between IoT devices.

Code Examples of Using MQTT in C#

Publishing MQTT Messages in C#

await client.PublishAsync(
      "core/dynamic_graph/entity/227489", // Topic to publish to
      "{'2023': '👍'}"                    // Message to publish
).ConfigureAwait(false);

Subscribing MQTT Messages in C#

client.OnMessageReceived += (sender, args) =>
{ 
// Handle Message in args.PublishMessage
Console.WriteLine("Message Received: {}", args.PublishMessage.PayloadAsString)
}
client.SubscribeAsync("core/dg/entity/227489").ConfigureAwait(false);

The code examples in this post come from our blog post, HiveMQ MQTT C# Client (BETA), and you can find many more examples there.

MQTT Security Best Practices While Using C# MQTT Broker

It’s important to follow security practices when you’re implementing MQTT with C#. MQTT is designed with efficiency in mind, rather than security, and security is especially important in IoT use cases where devices have limited memory and computing capabilities. Fortunately, there are steps you can take to keep your C# MQTT applications secure. A secure network or VPN will add security to your applications. You can also use the security standard SSL/TLS for transport-level encryption. It will encrypt your data while it is being transmitted and verify identity on both sides. You can also implement security practices at the application level by using a client identifier, username, and password.

HiveMQ’s C# MQTT client supports SSL/TLS. To use SSL/TLS, specify that you want to use it while instantiating the client.

var options = new HiveMQClientOptions();
options.UseTLS = true;
var client = new HiveMQClient(options);

Use Case Examples for MQTT in C#

Developers can use C# to implement MQTT for IoT use cases such as remote monitoring, home automation, telemetry, and sensor networks. Using MQTT with C# can allow you to build applications to share data between devices in real-time with limited bandwidth. For example, you could write a C# application to subscribe to humidity data published to an MQTT broker and automate an application to send an alert if a greenhouse’s humidity rises above a set threshold.

FAQ’s on Implementing MQTT in C# 

  1. Can C# be used for real-time applications with MQTT?

    Answer: Yes, C# can be used with MQTT for real-time IoT applications.

  2. What are the advantages of using MQTT over HTTP in C#?

    Answer: MQTT has a smaller message size and is more efficient for IoT use cases than HTTP and supports environments with limited network connection and many devices.

  3. Can you use MQTT with C# without extensions?

    Answer: No, you have to install a C# MQTT client such as the HiveMQ C# MQTT client for .NET.

  4. How do you install the C# MQTT client?

    Answer: You can install the HiveMQ C# MQTT client by using the code

    dotnet add package HiveMQtt

Conclusion

Developers can use C# with MQTT to build efficient IoT applications and work with real-time data. When deciding how to build an application, consider your specific requirements, constraints, and project objectives to make an informed choice about using MQTT in your C# projects. Click here to learn more about HiveMQ MQTT Client libraries.

HiveMQ Team

The HiveMQ team loves writing about MQTT, Sparkplug, Industrial IoT, protocols, how to deploy our platform, and more. We focus on industries ranging from energy, to transportation and logistics, to automotive manufacturing. Our experts are here to help, contact us with any questions.

HiveMQ logo
Review HiveMQ on G2