Skip to content

C# / .NET ​

The official ConnectMQ.Mqtt package is a preconfigured MQTTnet client for ConnectMQ: TLS and MQTT 5 by default, with simple PublishAsync, SubscribeAsync and WaitForMessageAsync methods.

How it connects ​

C# / .NET application connecting to ConnectMQ A C# / .NET application uses ConnectMQ.Mqtt (NuGet) · built on MQTTnet to connect to broker.connectmq.com over MQTT 5 · TLS 8883 with a username, password and a client ID based on the issued client ID. The broker checks the client with the Broker API (credentials, client ID, ACL and plan limits) and delivers messages to the web console and other devices and services. Your codeEveryone else on the brokerConnectMQ CloudMQTT 5 · TLS 8883username · password · client ID <ISSUED_ID>_<suffix>authC# / .NET applicationConnectMQ.Mqtt (NuGet) · built on MQTTnetawait client.PublishAsync("acme/istanbul/assembly/line1/robot-01/telemetry", …);PublishAsync · SubscribeAsync · WaitForMessageAsync · worker servicesMQTT brokerbroker.connectmq.comTLS 8883 · WSS 8084 /mqtt · MQTT 3.1.1 and 5Broker APICredentials · client IDACL · plan limitsWeb consoleapp.connectmq.com · live topics · alertsDevices & servicesESP32 · ConnectMQ Edge · back ends · appsMQTT messagesConnection check (credentials, client ID, ACL)

Install ​

bash
dotnet add package ConnectMQ.Mqtt

Requires .NET 8 or later.

Publish and subscribe ​

csharp
using System.Text.Json;
using ConnectMQ.Mqtt;
using MQTTnet.Protocol;

await using var client = await ConnectMQClient.ConnectAsync(new ConnectMQOptions
{
    Transport = MqttTransport.Tls,                                                     // mqtts://broker.connectmq.com:8883
    ClientId = Environment.GetEnvironmentVariable("CMQ_CLIENT_ID") + "_dotnet-service", // issued client ID + "_" + suffix
    Username = Environment.GetEnvironmentVariable("CMQ_USERNAME"),
    Password = Environment.GetEnvironmentVariable("CMQ_PASSWORD"),
});

await using var sub = await client.SubscribeAsync("acme/istanbul/#", msg =>
    Console.WriteLine($"{msg.Topic}: {msg.Payload}"), MqttQualityOfServiceLevel.AtLeastOnce);

var reading = new { temperature = 41.8, cycleTime = 12.4 };
await client.PublishAsync("acme/istanbul/assembly/line1/robot-01/telemetry",
    JsonSerializer.Serialize(reading), MqttQualityOfServiceLevel.AtLeastOnce);

PublishAsync takes a string (sent as UTF-8) or a byte[], so serialize objects to JSON first. Disposing the subscription unsubscribes; disposing the client sends DISCONNECT. The underlying MQTTnet client is available as client.Mqtt.

Always set ClientId

Without ClientId the package uses a random net-... ID, which your private broker refuses with Client identifier not valid (0x85). Use your issued client ID plus a suffix that is unique per process (why).

Request and reply ​

csharp
// Start waiting before you publish, so the reply cannot be missed
var reply = client.WaitForMessageAsync("acme/istanbul/assembly/line1/robot-01/reply", TimeSpan.FromSeconds(10));
await client.PublishAsync("acme/istanbul/assembly/line1/robot-01/cmd", """{"action":"home"}""");
Console.WriteLine((await reply).Payload); // throws TimeoutException after 10 s

Each ConnectMQMessage has Topic, Payload (UTF-8 string), RawPayload, Qos, Retain and Received. To clear a retained message, publish an empty payload with retain: true.

Worker service ​

csharp
public sealed class TelemetryWorker(IConfiguration config) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await using var client = await ConnectMQClient.ConnectAsync(new ConnectMQOptions
                {
                    ClientId = config["ConnectMQ:ClientId"] + "_worker",
                    Username = config["ConnectMQ:Username"],
                    Password = config["ConnectMQ:Password"],
                }, stoppingToken);

                while (client.IsConnected && !stoppingToken.IsCancellationRequested)
                {
                    var json = JsonSerializer.Serialize(new { cpu = Random.Shared.Next(100) });
                    await client.PublishAsync("acme/istanbul/it/servers/app-01/telemetry", json, cancellationToken: stoppingToken);
                    await Task.Delay(5000, stoppingToken);
                }
            }
            catch (Exception) when (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(5000, stoppingToken); // broker unreachable: try again
            }
        }
    }
}

The client does not reconnect on its own. The outer loop above connects again when IsConnected turns false or a publish fails.

Options ​

ConnectMQOptionsDefaultNotes
TransportMqttTransport.TlsTls 8883, SecureWebSocket 8084, Tcp 1883, WebSocket 8083
Hostbroker.connectmq.com
ClientIdnet- + randomSet it to <issued client ID>_<suffix>
Username, PasswordnoneFrom MQTT Connection Settings
ProtocolVersionV500 (MQTT 5)
KeepAlive, Timeout60 s, 10 s
ConfigurenoneAction<MqttClientOptionsBuilder> for a last will and other MQTTnet options

TLS checks the broker certificate against the system CA store; you do not need certificate files. If port 8883 is blocked on your network, use MqttTransport.SecureWebSocket.

Notes ​

  • If you see a connect/disconnect loop, another client is using the same client ID: see Client IDs & sessions.
  • ConnectMQBroker.TestAsync(MqttTransport.Tls) checks connectivity and round-trip time against the public test broker without an account.

Fully managed MQTT broker for connected devices.