要使用C#的MQTTNet库有效地连接到MQTT代理,请遵循以下步骤:
Install-Package MQTTNet
using MQTTNet;
using MQTTNet.Client;
using MQTTNet.Client.Options;
using System;
using System.Threading.Tasks;
IMqttClient mqttClient = new MqttClient("your_mqtt_broker_address");
将your_mqtt_broker_address
替换为您的MQTT代理地址(例如,“tcp://broker.hivemq.com:1883”)。
mqttClient.Connected += MqttClient_Connected;
mqttClient.Disconnected += MqttClient_Disconnected;
mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
private async Task MqttClient_Connected(object sender, MqttConnectedEventArgs e)
{
Console.WriteLine("Connected to MQTT broker.");
Console.WriteLine("Publishing will be started.");
// 订阅主题
var subscribeOptions = new MqttClientSubscribeOptions
{
TopicFilters = new[] { "your/topic" }
};
await mqttClient.SubscribeAsync(subscribeOptions);
}
private async Task MqttClient_Disconnected(object sender, MqttDisconnectedEventArgs e)
{
Console.WriteLine("Disconnected from MQTT broker.");
}
private async Task MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
{
Console.WriteLine($"Message received on topic '{e.Topic}': {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
}
public async Task ConnectAsync()
{
// 设置连接选项
var connectOptions = new MqttClientOptionsBuilder()
.WithTcpServer("your_mqtt_broker_address")
.WithClientId("your_client_id")
.WithCleanSession(true)
.WithKeepAlivePeriod(TimeSpan.FromSeconds(60))
.Build();
mqttClient = new MqttClient(connectOptions);
// 设置事件处理程序
mqttClient.Connected += MqttClient_Connected;
mqttClient.Disconnected += MqttClient_Disconnected;
mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
// 连接到MQTT代理
await mqttClient.ConnectAsync(connectOptions);
}
Main
方法中调用ConnectAsync
方法以启动连接:static async Task Main(string[] args)
{
await ConnectAsync();
}
现在,您的C#应用程序应该已成功连接到MQTT代理。请确保将your_mqtt_broker_address
、your_client_id
和your/topic
替换为您的实际MQTT代理地址、客户端ID和主题。