mqttnet3.0用法
.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用法的更多相关文章
- JS的javascript:void(0)用法
javascript:void(0)用法如下: <a href="javascript:void(0)"></a> // 执行js函数,0表示不执行函数. ...
- Excel学习笔记:if({1,0})用法
一.if函数 判断是否满足条件,满足则返回第2个参数,不满足则返回第3个参数. 使用格式:=if(A1>0,"正","负") 二.if({1,0})用法 ...
- javascript:void(0);用法及常见问题解析
void 操作符用法格式: javascript:void (expression) 下面的代码创建了一个超级链接,当用户以后不会发生任何事.当用户链接时,void(0) 计算为 0,但 Javasc ...
- Vue1.0用法详解
Vue.js 不支持 IE8 及其以下版本,因为 Vue.js 使用了 IE8 不能实现的 ECMAScript 5 特性. 开发环境部署 可参考使用 vue+webpack. 基本用法 1 2 3 ...
- 【转】char data[0]用法总结
@2019-07-31 struct MyData { int nLen; ]; }; 开始没有理解红色部分的内容,上网搜索下,发现用处很大,记录下来. 在结构中,data是一个数组名:但该数组没有元 ...
- vue2.0用法以及环境配置
一.配置环境搭建 1.安装node.js (可以去官网看) 2.安装git (推荐看廖雪峰文章,点击查看) 3.安装vue: cmd:npm install vue //最新稳定版本 npm inst ...
- js中 javascript:void(0) 用法详解
点击链接不做任何事情: <a href="#" onclick="return false">test</a> <a href=& ...
- C语言中do...while(0)用法小结
在linux内核代码中,经常看到do...while(0)的宏,do...while(0)有很多作用,下面举出几个: 本文地址:http://www.cnblogs.com/archimedes/p/ ...
- "javascript:void(0)"用法
1.window.open(''url'') 2.用自定义函数 <script> function openWin(tag,obj) { obj.target="_blank&q ...
随机推荐
- spring-cloud-gateway报错
2019-08-13 09:41:19.216 WARN [-,,,] 10084 --- [ main] ConfigServletWebServerApplicationContext : Exc ...
- 个人第四次作业AIpha2版本测试(最终版)
这个作业属于哪个课程 软件工程 作业要求在哪里 作业要求 团队名称 RainbowPlan团队博客 这个作业目标 手动测试非本团队的小组程序,是否可以正常登录,正常运行 一.测试人员信息 测试人员 姓 ...
- SpringBoot初级知识总结,太难了,未完待续.......
idea如何打包发布springboot 1.1.环境准备window系统,jdk8环境,springboot项目,maven3.5.4环境 1.2.进行打包发布 打开idea编辑器,打开一个写好的d ...
- FileNotFoundError: [WinError 2] 系统找不到指定的文件
用Idle运行Python脚本的时候发现如下错误: Traceback (most recent call last): File "D:\Python\Python36-32\lib\s ...
- Python PE8编程规范
参考博客:https://blog.csdn.net/weixin_39723544/article/details/82144280 1.使用四个空格而不是tab进行缩进 2.默认使用utf-8编码 ...
- GC原理---垃圾收集器
垃圾收集器 如果说收集算法是内存回收的方法论,垃圾收集器就是内存回收的具体实现 Serial收集器 串行收集器是最古老,最稳定以及效率高的收集器,可能会产生较长的停顿,只使用一个线程去回收.新生代.老 ...
- Typora常用快捷键
目录 无序列表:输入-之后输入空格 有序列表:输入数字+"."之后输入空格 任务列表:-[空格]空格 文字 标题:ctrl+数字 表格:ctrl+t 生成目录:按回车 选中一整行: ...
- 白话 spring AOP
------------------------------------ 剩下的时间不多了,抓经做自己想做的吧 AOP: 专业术语叫做面向切面的编程 为什么要使用aop: 为了简化代码, 将相同代码抽 ...
- jsp路径
访问静态资源的时候${pageContext.request.Context}没有作用,在浏览器F12调试的时候发现,路径并没有被解释为项目的根路径,而是没有解释出来,还是${pageContext. ...
- 每天一道Java题[8]
以下题目及解答属于个人见解,欢迎大家也分享和补充一下解答的内容,互相促进,共同进步! 题目 RESTful WebService与SOAP WebService有什么异同? 解答 SOAP是一个协议, ...