.net常用的mqtt类库有2个,m2mqtt和mqttnet两个类库

当然了,这两个库的教程网上一搜一大把

但mqttnet搜到的教程全是2.7及以下版本的,但3.0版语法却不再兼容,升级版本会导致很多问题,今天进行了成功的升级,现记录下来

参考文档地址:https://github.com/chkr1011/MQTTnet/wiki/Client

上代码:

 ///开源库地址:https://github.com/chkr1011/MQTTnet
///对应文档:https://github.com/chkr1011/MQTTnet/wiki/Client using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace MqttServerTest
{
public partial class mqtt测试工具 : Form
{
private IMqttClient mqttClient = null;
private bool isReconnect = true; public mqtt测试工具()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ } private async void BtnPublish_Click(object sender, EventArgs e)
{
await Publish();
} private async void BtnSubscribe_ClickAsync(object sender, EventArgs e)
{
await Subscribe();
} private async Task Publish()
{
string topic = txtPubTopic.Text.Trim(); if (string.IsNullOrEmpty(topic))
{
MessageBox.Show("发布主题不能为空!");
return;
} string inputString = txtSendMessage.Text.Trim();
try
{ var message = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(inputString)
.WithExactlyOnceQoS()
.WithRetainFlag()
.Build(); await mqttClient.PublishAsync(message);
}
catch (Exception ex)
{ Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($"发布主题失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
})));
} } private async Task Subscribe()
{
string topic = txtSubTopic.Text.Trim(); if (string.IsNullOrEmpty(topic))
{
MessageBox.Show("订阅主题不能为空!");
return;
} if (!mqttClient.IsConnected)
{
MessageBox.Show("MQTT客户端尚未连接!");
return;
} // Subscribe to a topic
await mqttClient.SubscribeAsync(new TopicFilterBuilder()
.WithTopic(topic)
.WithAtMostOnceQoS()
.Build()
);
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($"已订阅[{topic}]主题{Environment.NewLine}");
}))); } private async Task ConnectMqttServerAsync()
{
// Create a new MQTT client. if (mqttClient == null)
{
try
{
var factory = new MqttFactory();
mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder()
.WithTcpServer(txtIp.Text, Convert.ToInt32(txtPort.Text)).WithCredentials(txtUsername.Text, txtPsw.Text).WithClientId(txtClientId.Text) // Port is optional
.Build(); await mqttClient.ConnectAsync(options, CancellationToken.None);
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($"连接到MQTT服务器成功!" + txtIp.Text);
})));
mqttClient.UseApplicationMessageReceivedHandler(e =>
{ Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($"收到订阅消息!" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
}))); });
}
catch (Exception ex)
{ Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
})));
}
}
} private void MqttClient_Connected(object sender, EventArgs e)
{
Invoke((new Action(() =>
{
txtReceiveMessage.Clear();
txtReceiveMessage.AppendText("已连接到MQTT服务器!" + Environment.NewLine);
})));
} private void MqttClient_Disconnected(object sender, EventArgs e)
{
Invoke((new Action(() =>
{
txtReceiveMessage.Clear();
DateTime curTime = new DateTime();
curTime = DateTime.UtcNow;
txtReceiveMessage.AppendText($">> [{curTime.ToLongTimeString()}]");
txtReceiveMessage.AppendText("已断开MQTT连接!" + Environment.NewLine);
}))); //Reconnecting
if (isReconnect)
{
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText("正在尝试重新连接" + Environment.NewLine);
}))); var options = new MqttClientOptionsBuilder()
.WithClientId(txtClientId.Text)
.WithTcpServer(txtIp.Text, Convert.ToInt32(txtPort.Text))
.WithCredentials(txtUsername.Text, txtPsw.Text)
//.WithTls()
.WithCleanSession()
.Build();
Invoke((new Action(async () =>
{
await Task.Delay(TimeSpan.FromSeconds());
try
{
await mqttClient.ConnectAsync(options);
}
catch
{
txtReceiveMessage.AppendText("### RECONNECTING FAILED ###" + Environment.NewLine);
}
})));
}
else
{
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText("已下线!" + Environment.NewLine);
})));
}
} private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
{
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($">> {"### RECEIVED APPLICATION MESSAGE ###"}{Environment.NewLine}");
})));
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($">> Topic = {e.ApplicationMessage.Topic}{Environment.NewLine}");
})));
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($">> Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
})));
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($">> QoS = {e.ApplicationMessage.QualityOfServiceLevel}{Environment.NewLine}");
})));
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}");
})));
} private void btnLogIn_Click(object sender, EventArgs e)
{
isReconnect = true;
Task.Run(async () => { await ConnectMqttServerAsync(); });
} private void btnLogout_Click(object sender, EventArgs e)
{
isReconnect = false;
Task.Run(async () => { await mqttClient.DisconnectAsync(); });
} }
}

mqttnet3.0用法的更多相关文章

  1. JS的javascript:void(0)用法

    javascript:void(0)用法如下: <a href="javascript:void(0)"></a> // 执行js函数,0表示不执行函数. ...

  2. Excel学习笔记:if({1,0})用法

    一.if函数 判断是否满足条件,满足则返回第2个参数,不满足则返回第3个参数. 使用格式:=if(A1>0,"正","负") 二.if({1,0})用法 ...

  3. javascript:void(0);用法及常见问题解析

    void 操作符用法格式: javascript:void (expression) 下面的代码创建了一个超级链接,当用户以后不会发生任何事.当用户链接时,void(0) 计算为 0,但 Javasc ...

  4. Vue1.0用法详解

    Vue.js 不支持 IE8 及其以下版本,因为 Vue.js 使用了 IE8 不能实现的 ECMAScript 5 特性. 开发环境部署 可参考使用 vue+webpack. 基本用法 1 2 3 ...

  5. 【转】char data[0]用法总结

    @2019-07-31 struct MyData { int nLen; ]; }; 开始没有理解红色部分的内容,上网搜索下,发现用处很大,记录下来. 在结构中,data是一个数组名:但该数组没有元 ...

  6. vue2.0用法以及环境配置

    一.配置环境搭建 1.安装node.js (可以去官网看) 2.安装git (推荐看廖雪峰文章,点击查看) 3.安装vue: cmd:npm install vue //最新稳定版本 npm inst ...

  7. js中 javascript:void(0) 用法详解

    点击链接不做任何事情: <a href="#" onclick="return false">test</a> <a href=& ...

  8. C语言中do...while(0)用法小结

    在linux内核代码中,经常看到do...while(0)的宏,do...while(0)有很多作用,下面举出几个: 本文地址:http://www.cnblogs.com/archimedes/p/ ...

  9. "javascript:void(0)"用法

    1.window.open(''url'') 2.用自定义函数 <script> function openWin(tag,obj) { obj.target="_blank&q ...

随机推荐

  1. Webpack实战(三):作为前端你不得不懂的Webpack资源入口和出口的配置

    关于Webpack前两篇跟大家分享的主要是Webpack的一些基本的配置,今天开始我们详细了解一下有关Webpack的各种配置,今天主要跟大家分享的是Webpack的资源入口和资源出口的配置. 如果想 ...

  2. .NET Core开发的iNeuOS工业互联平台,iNeuKernel物联网核心组件在Docker容器中部署。

    目       录 1.      概述... 2 2.      演示信息... 2 3.      安装Docker容器... 2 4.      安装dotnet镜像... 3 5.      ...

  3. 分布式唯一ID的生成方案

    分布式ID的特性 全局唯一 不能出现重复的ID,这是最基本的要求. 递增 有利于关系数据库索引性能. 高可用 既然是服务于分布式系统,为多个服务提供ID服务,访问压力一定很大,所以需要保证高可用. 信 ...

  4. Oracle GoldenGate for DB2

    --Enable logdb2 update db cfg using LOGARCHMETH1 DISK:/home/db2inst1/arclogs--Rebootdb2 terminatedb2 ...

  5. [bzoj4824][洛谷P3757][Cqoi2017]老C的键盘

    Description 老 C 是个程序员. 作为一个优秀的程序员,老 C 拥有一个别具一格的键盘,据说这样可以大幅提升写程序的速度,还能让写出来的程序 在某种神奇力量的驱使之下跑得非常快.小 Q 也 ...

  6. webpack构建工具初始化并运行简单的demo

    webpack官网:https://webpack.js.org/ webpack是构建工具 安装webpack的前提:node,npm要安装 初始化项目 首先是初始化项目,创建一个文件夹,并且进入文 ...

  7. win10打开相机提示我们找不到你的相机

  8. HDU-2841 Visible Trees(莫比乌斯反演)

    Visible Trees 传送门 解题思路: 实际上的答案就是1~n与1~m之间互质的数的对数,写出式子就是 \(ans=\sum^{n}_{i=1}\sum^{m}_{j=1}[gcd(i,j)= ...

  9. ZJU-Reactor Cooling(无源汇有上下界最大流)

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2314 Reactor Cooling Time Limit: 5 ...

  10. C语言系列之预处理指令、循环左移函数的使用(四)

    本章节将讲两个知识点 第一个知识点:常用的预处理指令 第二个知识点:循环左移右移函数 第一个知识点:预处理指令 一种预处理指令是#define,他把名字A定义为P0,当这个名字出现在源文件的任何地方时 ...