.Net 示例
using System;
using System.Threading;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
class MqttClientExample
{
private MqttClient client;
private string broker;
private int port;
private string topic;
private string clientId;
private string username;
private string password;
private byte qos;
private bool isReconnecting = false;
// Constructor to initialize MQTT connection parameters
public MqttClientExample(string broker, int port, string topic, string clientId, string username, string password, byte qos)
{
this.broker = broker;
this.port = port;
this.topic = topic;
this.clientId = clientId;
this.username = username;
this.password = password;
this.qos = qos;
}
// Method to connect to the MQTT server
public void Connect()
{
try
{
// Create an MQTT client instance
client = new MqttClient(broker, port, false, null, null, MqttSslProtocols.None);
// Subscribe to the connection closed event
client.ConnectionClosed += Client_ConnectionClosed;
// Connect to the MQTT server
client.Connect(clientId, username, password);
if (client.IsConnected)
{
Console.WriteLine("Successfully connected to the MQTT server.");
// Subscribe to the specified topic
client.Subscribe(new string[] { topic }, new byte[] { qos });
// Handle received messages
client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
Console.WriteLine("Subscribed to topic: " + topic);
Console.WriteLine("Waiting for messages...");
}
else
{
Console.WriteLine("Failed to connect to the MQTT server.");
}
}
catch (Exception ex)
{
Console.WriteLine("Error occurred while connecting: " + ex.Message);
TryReconnect();
}
}
// Method to disconnect from the MQTT server
public void Disconnect()
{
if (client != null && client.IsConnected)
{
try
{
// Unsubscribe from the topic
client.Unsubscribe(new string[] { topic });
// Disconnect from the MQTT server
client.Disconnect();
Console.WriteLine("Disconnected from the MQTT server.");
}
catch (Exception ex)
{
Console.WriteLine("Error occurred while disconnecting: " + ex.Message);
}
}
}
// Method to attempt to reconnect to the MQTT server
private void TryReconnect()
{
if (isReconnecting) return;
isReconnecting = true;
new Thread(() =>
{
while (!client.IsConnected)
{
try
{
Console.WriteLine("Trying to reconnect to the MQTT server...");
client.Connect(clientId, username, password);
if (client.IsConnected)
{
Console.WriteLine("Reconnected successfully.");
// Resubscribe to the topic
client.Subscribe(new string[] { topic }, new byte[] { qos });
isReconnecting = false;
break;
}
}
catch (Exception ex)
{
Console.WriteLine("Reconnection failed: " + ex.Message);
}
Thread.Sleep(5000); // Try to reconnect every 5 seconds
}
}).Start();
}
// Event handler for the connection closed event
private void Client_ConnectionClosed(object sender, EventArgs e)
{
Console.WriteLine("The connection to the MQTT server has been closed.");
TryReconnect();
}
// Event handler for received messages
private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
// Process the received message
string message = System.Text.Encoding.UTF8.GetString(e.Message);
Console.WriteLine("Received message - Topic: " + e.Topic + ", Message content: " + message);
}
}
class Program
{
static void Main()
{
// MQTT server address
string broker = "mqtt.assetscontrols.com";
// MQTT server port
int port = 1883;
// Topic to subscribe to , {accessKey}.need to edit it.
string topic = "upload/ {accessKey}/+/#";
// Client ID any Custom Name
string clientId = "39440B3BD98045AC99EC2CF93EB15461_consumer01";
// Username web applicaton loginuser
string username = "XXXXX";
// Password web applicaton loginpass -MD532
string password = "XXXXX";
// QoS level
byte qos = 1;
MqttClientExample mqttClient = new MqttClientExample(broker, port, topic, clientId, username, password, qos);
mqttClient.Connect();
Console.WriteLine("Press any key to disconnect...");
Console.ReadKey();
mqttClient.Disconnect();
}
}
文档更新时间: 2025-03-15 14:59 作者:Jeson