Skip to content

Connect FlowMQ with MQTT .NET Client

FlowMQ's native support for MQTT v5.0 and v3.1.1 allows .NET developers to use powerful libraries like MQTTnet to build real-time applications. This guide provides a complete walkthrough for connecting to FlowMQ, publishing messages, and subscribing to topics using the MQTTnet client.

Prerequisites

Before you start, ensure you have the following:

  • A running instance of FlowMQ.
  • .NET 6 or later installed.
  • A .NET development environment, such as Visual Studio or the .NET CLI.

Installation

Add the MQTTnet package to your .NET project using the NuGet package manager.

bash
# Using .NET CLI
dotnet add package MQTTnet

# Or using Package Manager Console
Install-Package MQTTnet

Connecting to FlowMQ

First, you need to create an MQTT client and establish a connection to your FlowMQ broker.

csharp
using MQTTnet;
using MQTTnet.Client;
using System;
using System.Threading.Tasks;

public class MqttClientService
{
    private IMqttClient _mqttClient;

    public async Task ConnectAsync()
    {
        var factory = new MqttFactory();
        _mqttClient = factory.CreateMqttClient();

        var options = new MqttClientOptionsBuilder()
            .WithTcpServer("localhost", 1883) // Your FlowMQ broker address
            .WithClientId("my-dotnet-client")
            .Build();

        await _mqttClient.ConnectAsync(options, CancellationToken.None);

        Console.WriteLine("Successfully connected to FlowMQ.");
    }
}

Publishing Messages

Once connected, you can publish messages to any topic.

csharp
public async Task PublishAsync(string topic, string payload)
{
    var message = new MqttApplicationMessageBuilder()
        .WithTopic(topic)
        .WithPayload(payload)
        .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
        .Build();

    if (_mqttClient.IsConnected)
    {
        await _mqttClient.PublishAsync(message, CancellationToken.None);
        Console.WriteLine($"Message '{payload}' published to topic '{topic}'.");
    }
}

Subscribing to Topics

To receive messages, you need to subscribe to a topic and set up a handler for incoming messages.

Message Received Handler

This method will be called whenever a message is received on a subscribed topic.

csharp
private void HandleReceivedMessage(MqttApplicationMessageReceivedEventArgs e)
{
    Console.WriteLine($"Received message on topic '{e.ApplicationMessage.Topic}':");
    Console.WriteLine($"  Payload: {System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
}

Subscribing and Handling

csharp
public async Task SubscribeAsync(string topic)
{
    _mqttClient.ApplicationMessageReceivedAsync += e => {
        HandleReceivedMessage(e);
        return Task.CompletedTask;
    };

    var subscribeOptions = new MqttClientSubscribeOptionsBuilder()
        .WithTopicFilter(f => f.WithTopic(topic))
        .Build();

    await _mqttClient.SubscribeAsync(subscribeOptions, CancellationToken.None);

    Console.WriteLine($"Subscribed to topic '{topic}'.");
}

Full Example

Here is a simple console application that connects, subscribes, and publishes a message.

csharp
class Program
{
    static async Task Main(string[] args)
    {
        var mqttClientService = new MqttClientService();
        await mqttClientService.ConnectAsync();
        
        await mqttClientService.SubscribeAsync("flowmq/test");
        await mqttClientService.PublishAsync("flowmq/test", "Hello FlowMQ from .NET!");

        // Keep the application running to receive messages
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

Additional Resources

  • For more advanced features and detailed documentation, visit the official MQTTnet repository.
  • Explore FlowMQ's advanced features for MQTT.