MQTT Client Connectivity with .Net

Text Copied

Introduction

This guide walks you through creating a simple MQTT client using .NET and the MQTTnet library. The client will connect to an MQTT broker.

Setup & Dependencies

Before you begin, ensure the following are installed and configured:

  • .NET SDK (version 6.0 or later recommended)
    Check with:
  • dotnet --version

  • Access to an MQTT broker running locally or remotely
  • Add MQTTnet library to your project
    Navigate to your project directory and run:
  • dotnet add package MQTTnet --version 4.3.6.1152

MQTT Connect

This section covers various ways to connect to an MQTT broker using Python. Before proceeding, ensure your broker supports the desired connection method (TCP, TLS, WebSocket, etc.) and you have the correct connection parameters:

  • Broker Address
  • Port
  • Username/Password (if required)
  • CA Certificate (for TLS connections)

Basic TCP Connection


var options = new MqttClientOptionsBuilder()
.WithClientId("testClientDotNet4")
.WithTcpServer("localhost", 1883)
.Build();
// Create MQTT client
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
mqttClient.UseConnectedHandler(async e =>
{
    Console.WriteLine("Connected successfully with MQTT broker.");
});
// Connect to the MQTT broker
await mqttClient.ConnectAsync(options);


Connect with Authentication:


var options = new MqttClientOptionsBuilder()
.WithClientId("testclient")
.WithTcpServer("localhost", 1883)
.WithCredentials("username", "password") // Add username and password
.Build();


Connect over TLS/SSL


var options = new MqttClientOptionsBuilder()
.WithClientId("testcient")
.WithTcpServer(GetHostFromAddress(ADDRESS), GetPortFromAddress(ADDRESS))
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
    UseTls = true,
    Certificates = new List(), // Optionally add client certificates here
    CertificateValidationHandler = context =>
    {
        // Custom server certificate validation logic
        return context.SslPolicyErrors == System.Net.Security.SslPolicyErrors.None;
    },
    AllowUntrustedCertificates = false, // Do not allow untrusted certificates
    IgnoreCertificateChainErrors = false, // Do not ignore certificate chain errors
    IgnoreCertificateRevocationErrors = false // Do not ignore certificate revocation errors
})
.Build();

Connect via WebSocket


var options = new MqttClientOptionsBuilder()
.WithClientId("testclient")
.WithWebSocketServer("ws://localhost:10443/mqtt") // Use WebSocket server URI
.Build();

MQTT Publish


var message = new MqttApplicationMessageBuilder()
    .WithTopic(topic)
    .WithPayload($"Hello, MQTT! Message number {i}")
    .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
    .WithRetainFlag()
    .Build();
await mqttClient.PublishAsync(message);
await Task.Delay(1000); // Wait for 1 second

MQTT Subscribe

await mqttClient.SubscribeAsync(topic);

MQTT Disconnect

await mqttClient.DisconnectAsync();

Sample Client


using System.Security.Authentication;
using System.Text;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
class Program
{
    static async Task Main(string[] args)
    {
        string broker = "localhost";
        int port = 1883;
        string clientId = Guid.NewGuid().ToString();
        string topic = "sensor/data";
        // Create a MQTT client factory
        var factory = new MqttFactory();
        // Create a MQTT client instance
        var mqttClient = factory.CreateMqttClient();
        // Create MQTT client options
        var options = new MqttClientOptionsBuilder()
            .WithTcpServer(broker, port) // MQTT broker address and port
            .WithClientId(clientId)
            .WithCleanSession()
            .WithCredentials("username", "password") 
            // .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V500) //if you use mqtt version 5
            .Build();
        // Connect to MQTT broker
        var connectResult = await mqttClient.ConnectAsync(options);
        if (connectResult.ResultCode == MqttClientConnectResultCode.Success)
        {
            Console.WriteLine("Connected to MQTT broker successfully.");
            // Subscribe to a topic
            await mqttClient.SubscribeAsync(topic);
            // Callback function when a message is received
            mqttClient.ApplicationMessageReceivedAsync += e =>
            {
                Console.WriteLine($"Received message: {Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment)}");
                return Task.CompletedTask;
            };
            var message = new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload($"Hello, MQTT!")
                .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
                .WithRetainFlag()
                .Build();
            Console.WriteLine($"Publishing message: {Encoding.UTF8.GetString(message.PayloadSegment)}");
            await mqttClient.PublishAsync(message);
            await Task.Delay(1000); // Wait for 1 second
            // Unsubscribe and disconnect
            await mqttClient.UnsubscribeAsync(topic);
            await mqttClient.DisconnectAsync();
        }
        else
        {
            Console.WriteLine($"Failed to connect to MQTT broker: {connectResult.ResultCode}");
        }
    }
}

Run the following command to execute the program.

dotnet run

Scale .NET IoT Solutions Effortlessly!

High-performance, low-latency messaging
for mission-critical apps

Connect your .NET client to our MQTT broker to power large-scale IoT projects with reliability and security.