How To Use MQTT Client In .Net 7

MQTT (Message Queue Telemetry Transport) is a lightweight messaging protocol that is designed to be used in resource-constrained environments. MQTT is widely used in the Internet of Things (IoT) and machine-to-machine (M2M) communication.

This article will discuss how to implement an MQTT consumer in .NET 7. We will use the MQTTnet library, a high-performance MQTT client library in C#.

Setting up the Environment

To get started with .NET 7, you must install it on your system. You can download and install .NET 7 from the official website of .NET.

To use MQTTnet, you need to add the MQTTnet NuGet package to your project. You can do this using the NuGet package manager in Visual Studio or the dotnet CLI.

dotnet add package MQTTnet

Implementing an MQTT Consumer

You need to create a new console application to implement an MQTT consumer in .NET 7. In this example, we will subscribe to a topic and receive messages from the MQTT broker.

using System;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Client.Subscribing;
using MQTTnet.Protocol;
class Program {
    static async Task Main(string[] args) {
        var factory = new MqttFactory();
        var client = factory.CreateMqttClient();
        var options = new MqttClientOptionsBuilder().WithTcpServer("localhost", 1883).WithClientId("mqtt_consumer").Build();
        client.UseConnectedHandler(async e => {
            Console.WriteLine("Connected to MQTT broker.");
            var topicFilter = new MqttTopicFilterBuilder().WithTopic("test/topic").Build();
            await client.SubscribeAsync(new MqttClientSubscribeOptionsBuilder().WithTopicFilter(topicFilter).Build());
        });
        client.UseDisconnectedHandler(async e => {
            Console.WriteLine("Disconnected from MQTT broker.");
            await Task.Delay(TimeSpan.FromSeconds(5));
            try {
                await client.ConnectAsync(options, CancellationToken.None);
            } catch {
                Console.WriteLine("Reconnecting to MQTT broker failed.");
            }
        });
        client.UseApplicationMessageReceivedHandler(e => {
            Console.WriteLine($ "Received message on topic '{e.ApplicationMessage.Topic}': {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
        });
        try {
            await client.ConnectAsync(options, CancellationToken.None);
        } catch {
            Console.WriteLine("Connecting to MQTT broker failed.");
        }
        Console.ReadLine();
    }
}

The above code creates a new MQTT client and subscribes to the "test/topic" topic. When a message is received on this topic, the UseApplicationMessageReceivedHandler method is called, and the message is displayed on the console.

The UseConnectedHandler and UseDisconnectedHandler methods handle the connection and disconnection events. The UseConnectedHandler method is called when the client is connected to the MQTT broker, and the UseDisconnectedHandler method is called when the client is disconnected from the MQTT broker.

Conclusion

In this article, we discussed how to implement an MQTT consumer in .NET 7 using the MQTTnet library. We created a console application that subscribes to a topic and receives messages from the MQTT broker.

MQTT is a powerful messaging protocol that can be used in a variety of applications, including IoT and M2M communication. With the MQTTnet library, it is easy to implement an MQTT client in .NET 7, and the library provides a range of features.

Reference

Kindly refer to the portal for a free MQTT broker during testing.


Similar Articles