MQTT协议 C#客户端

版权声明:本文为博主原创文章,未经博主允许不得转载。http://blog.csdn.net/leytton https://blog.csdn.net/Leytton/article/details/51896738

1、引入M2MQTT的dll库文件

点击此处下载 M2Mqtt.Net.dll

2、建立客户端连接并订阅

//创建客户端实例
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS)); //主机为IP时
MqttClient client = new MqttClient(MQTT_BROKER_ADDRESS); //当主机地址为域名时

// 注册消息接收处理事件,还可以注册消息订阅成功、取消订阅成功、与服务器断开等事件处理函数
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; 

//生成客户端ID并连接服务器
string clientId = Guid.NewGuid().ToString(); 
client.Connect(clientId); 

// 订阅主题"/home/temperature" 消息质量为 2 
client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); 

... 

void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) 
{ 
//处理接收到的消息
string msg = System.Text.Encoding.Default.GetString(e.Message);
        textBox1.AppendText("收到消息:" + msg + "\r\n");
} 

3、发布消息

// 发布消息到主题 "/home/temperature" 消息质量为 2,不保留 
client.Publish("/home/temperature", Encoding.UTF8.GetBytes("hello"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); 

4、参考文献

https://github.com/mqtt/mqtt.github.io/wiki/libraries 

https://github.com/leytton/m2mqtt (防丢fork)

【转载请注明出处:http://blog.csdn.net/leytton/article/details/51896738


猜你喜欢

转载自blog.csdn.net/Leytton/article/details/51896738