C# and .NET MQTT 3.1.1 and 5.0

C# MQTT Client for MQTT 3.1.1 and 5.0

Connect C# apps to any MQTT broker over TCP or WebSocket with this .NET MQTT client, from .NET Framework 2.0 to .NET 10.

MQTT 3.1.1 and MQTT 5.0
QoS 0, 1 and 2
TLS over TCP or WebSocket
Last will, retain, keep-alive

Connect, subscribe and publish in C# → · See pricing →

C# MQTT client
using esegece.sgcWebSockets;

var client = new TsgcWebSocketClient();
client.Host = "broker.example.com";
client.Port = 8883;
client.TLS = true;
client.Specifications.RFC6455 = false; // MQTT over TCP

var mqtt = new TsgcWSPClient_MQTT();
mqtt.Client = client;
mqtt.MQTTVersion = TwsMQTTVersion.mqtt5;

mqtt.OnMQTTConnect += (conn, session, code, reason, props) =>
    mqtt.Subscribe("sensors/#");
mqtt.OnMQTTPublish += (conn, topic, text, props) =>
    Console.WriteLine(topic + ": " + text);

client.Active = true;

An MQTT client that rides on the sgcWebSockets client

One transport component, one protocol component, events for every MQTT packet.

The C# MQTT client in sgcWebSockets .NET is TsgcWSPClient_MQTT, in the esegece.sgcWebSockets namespace. It does not open sockets itself. You assign a TsgcWebSocketClient to its Client property, and that client carries the MQTT packets either as a plain TCP stream (ports 1883 and 8883) or inside WebSocket frames for brokers that expose an MQTT over WebSocket endpoint. Host, port, TLS, proxy and auto-reconnect stay on the transport, the MQTT session, topics and QoS live on the protocol component.

Every broker reply becomes a C# event: OnMQTTConnect, OnMQTTPublish, OnMQTTSubscribe, OnMQTTPubAck, OnMQTTPubRec, OnMQTTPubComp, OnMQTTPing and OnMQTTDisconnect, plus OnMQTTAuth for MQTT 5.0 enhanced authentication. The same package targets .NET Framework 2.0 to 4.8.1, .NET Core 1.0 to 3.1, .NET 5 to .NET 10 and .NET Standard 1.6 and 2.0, on Windows, Linux and macOS.

MQTT 3.1.1 and 5.0

Choose the protocol with MQTTVersion: TwsMQTTVersion.mqtt311 or TwsMQTTVersion.mqtt5.

TCP or WebSocket

Specifications.RFC6455 = false on the transport sends raw MQTT over TCP; leave it on to tunnel MQTT through a WebSocket path.

Three QoS levels

TmqttQoS.mtqsAtMostOnce, mtqsAtLeastOnce and mtqsExactlyOnce on every publish and subscribe.

Session control

Username and password in Authentication, keep-alive pings in HeartBeat, a last will in LastWillTestament.

Connect, subscribe and publish in C#

Install the esegece.sgcWebSockets NuGet package (or esegece.sgcWebSockets.Community), then follow the four steps.

using esegece.sgcWebSockets;

// transport: TCP with TLS on the standard secure MQTT port
var client = new TsgcWebSocketClient();
client.Host = "broker.example.com";
client.Port = 8883;
client.TLS = true;
client.TLSOptions.Version = TwsTLSVersions.tls1_2;
client.Specifications.RFC6455 = false;   // raw MQTT, no WebSocket handshake

// protocol: MQTT 3.1.1 with credentials and keep-alive
var mqtt = new TsgcWSPClient_MQTT();
mqtt.Client = client;
mqtt.MQTTVersion = TwsMQTTVersion.mqtt311;
mqtt.Authentication.Enabled = true;
mqtt.Authentication.UserName = "device-01";
mqtt.Authentication.Password = "secret";
mqtt.HeartBeat.Enabled = true;
mqtt.HeartBeat.Interval = 30;

mqtt.OnMQTTConnect += (conn, session, reasonCode, reasonName, props) =>
    Console.WriteLine("#mqtt connected: " + reasonName);
mqtt.OnMQTTDisconnect += (conn, reasonCode, reasonName, props) =>
    Console.WriteLine("#mqtt disconnected: " + reasonName);

client.Active = true;
// subscribe once the broker has accepted the session
mqtt.OnMQTTConnect += (conn, session, reasonCode, reasonName, props) =>
{
    mqtt.Subscribe("sensors/+/temperature");
    mqtt.Subscribe("alerts/#", TmqttQoS.mtqsExactlyOnce, null);
};

mqtt.OnMQTTSubscribe += (conn, packetId, codes, props) =>
    Console.WriteLine("#subscribed, packet " + packetId);

// every message on a subscribed topic arrives here
mqtt.OnMQTTPublish += (conn, topic, text, props) =>
    Console.WriteLine(topic + " = " + text);

// stop receiving a topic
mqtt.UnSubscribe("alerts/#");
// QoS 0: fire and forget
mqtt.Publish("sensors/room1/temperature", "21.5");

// QoS 1 with the retain flag, so late subscribers get the last value
mqtt.Publish("devices/device-01/status", "online", TmqttQoS.mtqsAtLeastOnce, true);

// QoS 2: wait up to 10 seconds for the broker to confirm
bool ok = mqtt.PublishAndWait("orders/new", "{\"id\": 42}", TmqttQoS.mtqsExactlyOnce, 10000);

// binary payloads
mqtt.Publish("images/cam1", File.ReadAllBytes("frame.jpg"));

// acknowledgements
mqtt.OnMQTTPubAck  += (conn, packetId, reasonCode, reasonName, props) =>
    Console.WriteLine("#puback " + packetId);
mqtt.OnMQTTPubComp += (conn, packetId, reasonCode, reasonName, props) =>
    Console.WriteLine("#pubcomp " + packetId);
using esegece.sgcWebSockets;

// the same MQTT client, tunnelled through a secure WebSocket (wss://)
var client = new TsgcWebSocketClient();
client.Host = "broker.example.com";
client.Port = 443;
client.TLS = true;
client.Options.Parameters = "/mqtt";   // the broker's WebSocket path
client.WatchDog.Enabled = true;          // reconnect after network drops

var mqtt = new TsgcWSPClient_MQTT();
mqtt.Client = client;
mqtt.OnMQTTPublish += (conn, topic, text, props) => Console.WriteLine(topic + ": " + text);

client.Active = true;

The WinForms demos MQTT Client and MQTT Console in the .NET download wire the same calls to a form, with a broker list, TLS and proxy settings, QoS and retain options.

MQTT QoS 0, 1 and 2 from C#

Pass a TmqttQoS value to Publish, PublishAndWait or Subscribe. At QoS 1 and 2 the client resends a message when the acknowledgement does not arrive in time. Handle OnMQTTPubAck or OnMQTTPubComp to track delivery, or call PublishAndWait, which returns false when the broker gives no response within the timeout (10 seconds by default).

QoSC# valueDeliveryConfirmation event
0TmqttQoS.mtqsAtMostOnceAt most once, best effort, no replynone
1TmqttQoS.mtqsAtLeastOnceAt least once, acknowledged by the brokerOnMQTTPubAck
2TmqttQoS.mtqsExactlyOnceExactly once, four step handshakeOnMQTTPubRec, OnMQTTPubComp

TLS, credentials, last will and keep-alive

TLS on port 8883

Set TLS = true on the transport and choose the protocol in TLSOptions.Version, up to TLS 1.3. For brokers that require client certificates, TLSOptions also takes CertFile, KeyFile, Password and RootCertFile, and VerifyCertificate checks the server certificate.

Username and password

Authentication.Enabled, Authentication.UserName and Authentication.Password go into the CONNECT packet.

Last will

LastWillTestament sets Topic, Text, QoS and Retain, so the broker publishes an "offline" message when a device drops without a clean disconnect.

Keep-alive

HeartBeat.Enabled and HeartBeat.Interval send PINGREQ packets; OnMQTTPing reports each response, and Ping() sends one on demand.

Client id and clean session

OnMQTTBeforeConnect passes CleanSession and ClientIdentifier by reference, so you choose a persistent session and a fixed client id per device.

Proxy and reconnect

The transport's Proxy settings and WatchDog auto-reconnect apply to MQTT unchanged.

mqtt.LastWillTestament.Enabled = true;
mqtt.LastWillTestament.Topic = "devices/device-01/status";
mqtt.LastWillTestament.Text = "offline";
mqtt.LastWillTestament.QoS = TmqttQoS.mtqsAtLeastOnce;
mqtt.LastWillTestament.Retain = true;

mqtt.OnMQTTBeforeConnect += (TsgcWSConnection conn, ref bool cleanSession, ref string clientId) =>
{
    cleanSession = false;
    clientId = "device-01";
};

MQTT 5.0 features in C#

Set MQTTVersion = TwsMQTTVersion.mqtt5 and the client speaks MQTT 5.0. Every acknowledgement event then carries the broker's ReasonCode and ReasonName together with the packet properties, so failures arrive with a reason instead of a dropped connection.

Connect properties

ConnectProperties sets SessionExpiryInterval, ReceiveMaximum, MaximumPacketSize, TopicAliasMaximum, UserProperties and request flags for response and problem information.

Publish properties

Per message ContentType, ResponseTopic, CorrelationData, MessageExpiryInterval, TopicAlias, PayloadFormat and user properties for request and response patterns.

Enhanced authentication

Auth() sends AUTH packets with an AuthenticationMethod and AuthenticationData, including re-authentication, and OnMQTTAuth receives the broker's challenge.

Will and disconnect properties

A will delay interval and message expiry on the last will, plus a reason code, reason string and session expiry on Disconnect.

mqtt.MQTTVersion = TwsMQTTVersion.mqtt5;
mqtt.ConnectProperties.Enabled = true;
mqtt.ConnectProperties.SessionExpiryInterval = 3600;   // keep the session one hour
mqtt.ConnectProperties.ReceiveMaximum = 100;

mqtt.OnMQTTConnect += (conn, session, reasonCode, reasonName, props) =>
    Console.WriteLine("CONNACK " + reasonCode + " " + reasonName);

Any standard MQTT broker, plus AWS IoT and Azure IoT

Because the client follows the MQTT 3.1.1 and 5.0 specifications, it connects to self-hosted and managed brokers alike: on port 1883 for plain TCP, 8883 for TLS, or the broker's WebSocket path when only HTTPS ports are open. For the cloud IoT platforms, sgcWebSockets .NET also ships an AWS IoT client for AWS IoT Core and an Azure IoT client for Azure IoT Hub, both MQTT based, listed in the .NET feature matrix.

The same library also gives you AMQP 0.9.1 and 1.0, STOMP, Kafka and the C# WebSocket client and server, so one dependency covers every messaging protocol in the application.

Free to start, one price for every protocol

The MQTT client is in every .NET edition. Community is free for commercial and non-commercial use by small teams (under EUR 1M revenue, up to 5 developers), with the full feature set and a startup notice. Professional removes the notice and starts at €149 per developer with 1 year of updates; Enterprise adds the source code for rebuilding the assemblies. Team and Site licences are on the pricing page (.NET tab).

C# MQTT questions

Create a TsgcWebSocketClient with the broker's Host and Port, set Specifications.RFC6455 = false for a plain TCP broker, create a TsgcWSPClient_MQTT and assign the client to its Client property. Setting client.Active = true opens the connection, and OnMQTTConnect fires when the broker accepts the session.

Yes. Set MQTTVersion to TwsMQTTVersion.mqtt5 for MQTT 5.0 or TwsMQTTVersion.mqtt311 for MQTT 3.1.1. MQTT 5.0 adds reason codes on every acknowledgement, connect and publish properties, user properties and enhanced authentication.

Call Publish(topic, text, TmqttQoS.mtqsAtLeastOnce) or TmqttQoS.mtqsExactlyOnce, optionally with a retain flag. Use PublishAndWait when the code must know the broker processed the message: it returns false if no response arrives within the timeout.

Yes. Set Port = 8883 and TLS = true on the TsgcWebSocketClient, choose the version in TLSOptions.Version (up to TLS 1.3) and add TLSOptions.CertFile and KeyFile if the broker asks for a client certificate.

Yes, that is the transport's default. Leave Specifications.RFC6455 on, set Options.Parameters to the broker's WebSocket path (for example /mqtt) and use TLS = true on port 443 for wss://. This gets MQTT through firewalls that only allow HTTPS.

.NET Framework 2.0 to 4.8.1, .NET Core 1.0 to 3.1, .NET 5 to .NET 10 and .NET Standard 1.6 and 2.0, on Windows, Linux and macOS. Install esegece.sgcWebSockets or the free esegece.sgcWebSockets.Community package from nuget.org.

Yes. The Community edition includes the MQTT client and is free for commercial and non-commercial use by small teams (under EUR 1M revenue, up to 5 developers), with a startup notice. Larger organizations buy Professional, from €149 per developer, or Enterprise.

More on sgcWebSockets .NET

C# WebSocket library

The WebSocket client and server that carry the MQTT traffic, with TLS, compression and auto-reconnect.

.NET feature matrix

Every component and protocol in the .NET editions, MQTT, AMQP, STOMP, AWS IoT and Azure IoT included.

Download

Community edition, NuGet packages and the compiled .NET demos, MQTT Client and MQTT Console among them.

Also for Delphi and C++Builder

The same MQTT client is available for Delphi and C++Builder, with the same TsgcWSPClient_MQTT class and events.

Best value: All-AccessEvery eSeGeCe product, Premium Support included, from €1,059/year.
See All-Access pricing

Publish your first MQTT message from C# today

Download the trial or install esegece.sgcWebSockets.Community from NuGet. Professional from €149 per developer.