下面是使用C#编写的MQTTNet客户端示例代码,可以用于连接MQTT服务器并发布和订阅MQTT消息:
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Extensions.ManagedClient;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MqttNetClientExample
class Program
static async Task Main(string[] args)
var factory = new MqttFactory();
var mqttClient = factory.CreateManagedMqttClient();
// 配置MQTT客户端选项
var options = new MqttClientOptionsBuilder()
.WithClientId("clientId")
.WithTcpServer("localhost", 1883) // MQTT服务器地址和端口
.Build();
// 配置MQTT客户端回调函数
mqttClient.UseApplicationMessageReceivedHandler(e =>
Console.WriteLine($"Topic: {e.ApplicationMessage.Topic}, Payload: {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
// 连接到MQTT服务器
await mqttClient.StartAsync(new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(options)
.Build());
// 发布MQTT消息
var message = new MqttApplicationMessageBuilder()
.WithTopic("test/topic")
.WithPayload("Hello MQTT")
.WithExactlyOnceQoS()
.WithRetainFlag()
.Build();
await mqttClient.PublishAsync(message);
// 订阅MQTT主题
await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder()
.WithTopic("test/topic")
.WithExactlyOnceQoS()
.Build());
// 等待MQTT消息
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
// 断开MQTT连接
await mqttClient.StopAsync();
在此示例中,使用了MQTTNet库,它是一个支持.NET Standard的MQTT客户端库。首先,创建一个MqttFactory
实例来创建一个ManagedMqttClient
,然后创建一个MqttClientOptionsBuilder
实例来配置MQTT客户端选项。接着,配置MQTT客户端回调函数,以处理收到的MQTT消息。然后,使用ManagedMqttClientOptionsBuilder
创建ManagedMqttClient
选项并启动MQTT客户端,连接到MQTT服务器。然后,使用MqttApplicationMessageBuilder
创建一个MQTT消息,使用PublishAsync
方法发布该消息,并使用MqttTopicFilterBuilder
订阅MQTT主题。最后,使用StopAsync
方法断开MQTT连接。
请注意,这只是MQTTNet客户端的基本示例,您可以根据需要对其进行更改和扩展,以满足您的特定需求。