We always see Python or Node.js examples in IoT, but C# is just as easy, robust, and secure. In this quick tutorial we will:
- Connect our .NET client to a public broker, like: HiveMQ.
- Subscribe to a topic:
iot/door/status
. - Display incoming messages in the console.
What you need
- .NET 8 SDK
- The MQTTnet library
- A public MQTT broker (
broker.hivemq.com:1883
) - And a willingness to automate and experiment!
Example code
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using System;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
// 1. Configure client options
var options = new MqttClientOptionsBuilder()
.WithTcpServer("broker.hivemq.com", 1883)
.WithClientId("dotnet-iot-demo")
.Build();
// 2. Create the client and define handlers
var factory = new MqttFactory();
var client = factory.CreateMqttClient();
client.UseConnectedHandler(async _ =>
{
Console.WriteLine("Connected to HiveMQ");
await client.SubscribeAsync("iot/door/status");
Console.WriteLine("Subscribed to: iot/door/status");
});
client.UseApplicationMessageReceivedHandler(e =>
{
var payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
Console.WriteLine($"Message received: {payload}");
// Here you could, for example:
// • Log the event to your database
// • Trigger an email or SMS alert
// • Send the data to a web dashboard
});
// 3. Connect and wait for messages
await client.ConnectAsync(options);
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();
}
}
Top comments (0)