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
Install
dotnet add package ConnectMQ.MqttRequires .NET 8 or later.
Publish and subscribe
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
// 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 sEach 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
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
ConnectMQOptions | Default | Notes |
|---|---|---|
Transport | MqttTransport.Tls | Tls 8883, SecureWebSocket 8084, Tcp 1883, WebSocket 8083 |
Host | broker.connectmq.com | |
ClientId | net- + random | Set it to <issued client ID>_<suffix> |
Username, Password | none | From MQTT Connection Settings |
ProtocolVersion | V500 (MQTT 5) | |
KeepAlive, Timeout | 60 s, 10 s | |
Configure | none | Action<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.