要使用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和主題。