深度优先

这个家伙好懒,除了文章什么都没留下

0%

【MQTT】.Net Core 操作

1、安装M2MQTT

注:.Net Core 项目是安装M2MqttDotnetCore

2、建立连接/订阅/发送消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{

MqttClient client = new MqttClient("IPAddress");

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

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

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


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

Console.ReadLine();
}

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

3、参考文献

https://github.com/mohaqeq/paho.mqtt.m2mqtt

https://blog.csdn.net/Leytton/article/details/51896738