HiveMQ Logo
HiveMQ MQTT C# Client (BETA)

HiveMQ MQTT C# Client (BETA)

author Peter Giacomo Lombardo

Written by Peter Giacomo Lombardo

Category: MQTT C Sharp MQTT Client. .Net

Published: March 30, 2023

HiveMQ created the MQTT C# Client as part of our larger efforts to offer the MQTT community reliable, tested, performant, and maintained MQTT clients. No longer are you limited to choosing from anonymous third-party MQTT clients who aren’t maintained, updated, or supported. HiveMQ aims to provide the community with clients with a clear path for features, fixes, and support - critical requirements to assure your devices are always functioning at full potential and your business is running without issue.

Introduction to the HiveMQ MQTT C# Client

HiveMQ MQTT C# Client
Language C# for .NET 6.0 and greater
License Apache License 2.0
Website github.com/hivemq/hivemq-mqtt-client-dotnet
API Style Asynchronous

The new MQTT client for C# is in BETA, open source (available on Github), and licensed under the permissive Apache 2.0 License. We’re proud to open source this project for transparency and to welcome community input or contributions. The client currently features full MQTT 5.0 support and aims to be compatible with all major MQTT brokers - regardless of vendor. Notable features of the client are an extensive event system that allows you to hook into any client functionality, from message handling down to packet delivery. As a feature of MQTT 5.0, it also supports back pressure handling to manage the load on your devices by communicating throughput limits. TLS, basic authentication and all Quality of Service (QoS) levels are supported - and more is to come. As this client matures, this post will be updated to reflect the latest changes and additions.

Key features of the HiveMQ C# Client

Feature
MQTT 3.1.1 Coming Soon
MQTT 5.0 ok
SSL/TLS ok
WebSocket Transport Coming Soon
QoS 0 ok
QoS 1 ok
QoS 2 ok
Authentication ok
Backpressure Handling ok

How to use the HiveMQ MQTT C# Client

Installation

The HiveMQ MQTT C# Client is available as a Nuget package hosted on NuGet.org. To install:

1
dotnet add package HiveMQtt

Creating the Client

The HiveMQ MQTT C# Client can be instantiated with smart defaults as simply as:

1
2
using HiveMQtt.Client;
var client = new HiveMQClient();

Instantiating the client with default settings as in the previous example assumes an MQTT broker on localhost:1883. But if you need to override that address, there is the HiveMQClientOptions class:

1
2
3
4
5
6
var options = new HiveMQClientOptions();
options.Host = 'candy.x39.eu.hivemq.cloud';
options.Port = 8883;
options.UseTLS = true;

var client = new HiveMQClient(options);

Passing in the HiveMQClientOptions structure, you can customize client settings and behaviour. This class has many options available; see all the options available.

Connecting with Authentication

This example shows how to provide simple authentication credentials:

1
2
3
4
5
6
var options = new HiveMQClientOptions();
options.UserName = 'hivemq-user-2938r02';
options.Password = Environment.GetEnvironmentVariable("HMQ_PASS");

var client = new HiveMQClient(options);
var connectResult = await client.ConnectAsync().ConfigureAwait(false);

Connecting with an After Event

You can hook into the AfterConnect event to take any action as follows. Similar events exist for Before/AfterSubscribe, OnMessageReceived, OnDisconnectReceived and many more.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var client = new HiveMQClient();

void AfterConnectHandler(object? sender, AfterConnectEventArgs eventArgs)
{
    // Take action post connection with:
    // sender as HiveMQClient and eventArgs.ConnectResult
}

client.AfterConnect += AfterConnectHandler;
var connectResult = await client.ConnectAsync().ConfigureAwait(false);

Publish

In order to build and execute a publish, you would use code similar to the below:

1
2
3
4
await client.PublishAsync(
    "core/dynamic_graph/entity/227489", // Topic to publish to
    "{'2023': '👍'}"                    // Message to publish
).ConfigureAwait(false);

There are variations on Publish that allow you to control how and what is published. See the available calls and MQTT5PublishMessage.

Subscribe

When creating a subscription, you provide an event callback handler which is used for each incoming message via the OnMessageReceived event:

1
2
3
4
5
6
7
client.OnMessageReceived += (sender, args) =>
{
    // Handle Message in args.PublishMessage
    Console.WriteLine("Message Received: {}", args.PublishMessage.PayloadAsString)
}

client.SubscribeAsync("core/dg/entity/227489").ConfigureAwait(false);

See also: HiveMQClient events

Unsubscribe

To unsubscribe from a topic, simply call UnsubscribeAsync with the topic to unsubscribe from

1
client.UnsubscribeAsync("core/dynamic_graph/entity/227489")

If you want to view your existing subscriptions, they are always stored in client.Subscriptions.

Disconnect

Just call client.DisconnectAsync() on the client object created previously.

SSL / TLS

In order to use SSL / TLS for connecting to the broker, you simply specify its usage while building the client:

1
2
3
4
var options = new HiveMQClientOptions();
options.UseTLS = true;

var client = new HiveMQClient(options);

References & See Also

The HiveMQtt Client for C# on .NET

HiveMQ Support & Community

Other HiveMQ MQTT Clients

Summary

This is just the beginning of the story for HiveMQ and C#. We welcome you to try out the new client, browse the source code and contact us if you have any issues, comments or questions.

You can reach out to us on Github or in our Community Forum.

author Peter Giacomo Lombardo

About Peter Giacomo Lombardo

Peter is a Staff Software Engineer at HiveMQ leading the effort to create best-of-breed MQTT & Sparkplug clients for the great HiveMQ community and beyond.

Follow Peter on LinkedIn and Github

mail icon Contact HiveMQ
newer posts The HiveMQ MQTT Client Library for Java and Its Blocking API Flavor
HiveMQ Cloud Integrates Confluent Cloud and Aiven Kafka Services older posts