原标题:C# 接受MQTT服务器推送的消息
前言:
MQTT是IBM开发的一个即时通讯协议。MQTT是面向M2M和物联网的连接协议,采用轻量级发布和订阅消息传输机制。
大家可以直接上GitHub下载MQQT服务的源码,源码地址:https://github.com/mqtt/mqtt.github.io/wiki/libraries
主要内容:
官方文档翻译:
M2Mqtt库提供了一个主类MqttClient,代表连接到代理的MQTT客户端。您可以连接到提供其IP地址或主机名的代理,以及可选的与MQTT协议相关的一些参数。
连接到代理后,您可以使用Publish()方法向主题和Subscribe()方法发布消息以订阅主题并接收其上发布的消息。
MqttClient类是基于事件,以便您在邮件发布到您订阅的主题时收到一个事件。消息发布完成后,您可以收到事件,您已订阅或取消订阅主题。
以客户端为主题的例子:
...
// create client instance
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));
// register to message received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
// subscribe to the topic "/home/temperature" with QoS 2
client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
...
static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
// handle message received
}
一般C#客户端都是应用单例模式,下面的是我封装的类:
public class MqttClientService
{
private static volatile MqttClientService _instance = null;
private static readonly object LockHelper = new object();
///
/// 创建单例模式
///
///
///
public static MqttClientService CreateInstance(string ipAddress)
{
if (_instance == null)
{
lock (LockHelper)
{
if (_instance == null)
_instance = new MqttClientService(ipAddress);
}
}
return _instance;
}
///
/// 实例化订阅客户端
///
public MqttClient SubscribeClient { get; set; }
public Action ClientPublishReceivedAction { get; set; }
public MqttClientService(string ipAddress)
{
// create client instance
SubscribeClient = new MqttClient(IPAddress.Parse(ipAddress));
// register to message received
SubscribeClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
string clientId = Guid.NewGuid().ToString();
SubscribeClient.Connect(clientId);
// subscribe to the topic "/home/temperature" with QoS 2
SubscribeClient.Subscribe(new string[] { "avatar/uploaded" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
}
void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
// handle message received
ClientPublishReceivedAction.Invoke(sender, e);
}
public void client_MqttMsgPublish(string publishString)
{
SubscribeClient.Publish("avatar/signed", Encoding.UTF8.GetBytes(publishString), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
}
}
用户只需要把订阅的路径写到Subscribe即可。
使用 MQTTnet 快速实现 MQTT 通信