0
点赞
收藏
分享

微信扫一扫

【MQTT】.Net Core 操作


1、安装M2MQTT

【MQTT】.Net Core 操作_Text

 注:.Net Core 项目是安装M2MqttDotnetCore

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

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​​

举报

相关推荐

0 条评论