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

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

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

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

上代码:

  1. ///开源库地址:https://github.com/chkr1011/MQTTnet
  2. ///对应文档:https://github.com/chkr1011/MQTTnet/wiki/Client
  3.  
  4. using MQTTnet;
  5. using MQTTnet.Client;
  6. using MQTTnet.Client.Options;
  7. using System;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows.Forms;
  12.  
  13. namespace MqttServerTest
  14. {
  15. public partial class mqtt测试工具 : Form
  16. {
  17. private IMqttClient mqttClient = null;
  18. private bool isReconnect = true;
  19.  
  20. public mqtt测试工具()
  21. {
  22. InitializeComponent();
  23. }
  24.  
  25. private void Form1_Load(object sender, EventArgs e)
  26. {
  27.  
  28. }
  29.  
  30. private async void BtnPublish_Click(object sender, EventArgs e)
  31. {
  32. await Publish();
  33. }
  34.  
  35. private async void BtnSubscribe_ClickAsync(object sender, EventArgs e)
  36. {
  37. await Subscribe();
  38. }
  39.  
  40. private async Task Publish()
  41. {
  42. string topic = txtPubTopic.Text.Trim();
  43.  
  44. if (string.IsNullOrEmpty(topic))
  45. {
  46. MessageBox.Show("发布主题不能为空!");
  47. return;
  48. }
  49.  
  50. string inputString = txtSendMessage.Text.Trim();
  51. try
  52. {
  53.  
  54. var message = new MqttApplicationMessageBuilder()
  55. .WithTopic(topic)
  56. .WithPayload(inputString)
  57. .WithExactlyOnceQoS()
  58. .WithRetainFlag()
  59. .Build();
  60.  
  61. await mqttClient.PublishAsync(message);
  62. }
  63. catch (Exception ex)
  64. {
  65.  
  66. Invoke((new Action(() =>
  67. {
  68. txtReceiveMessage.AppendText($"发布主题失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
  69. })));
  70. }
  71.  
  72. }
  73.  
  74. private async Task Subscribe()
  75. {
  76. string topic = txtSubTopic.Text.Trim();
  77.  
  78. if (string.IsNullOrEmpty(topic))
  79. {
  80. MessageBox.Show("订阅主题不能为空!");
  81. return;
  82. }
  83.  
  84. if (!mqttClient.IsConnected)
  85. {
  86. MessageBox.Show("MQTT客户端尚未连接!");
  87. return;
  88. }
  89.  
  90. // Subscribe to a topic
  91. await mqttClient.SubscribeAsync(new TopicFilterBuilder()
  92. .WithTopic(topic)
  93. .WithAtMostOnceQoS()
  94. .Build()
  95. );
  96. Invoke((new Action(() =>
  97. {
  98. txtReceiveMessage.AppendText($"已订阅[{topic}]主题{Environment.NewLine}");
  99. })));
  100.  
  101. }
  102.  
  103. private async Task ConnectMqttServerAsync()
  104. {
  105. // Create a new MQTT client.
  106.  
  107. if (mqttClient == null)
  108. {
  109. try
  110. {
  111. var factory = new MqttFactory();
  112. mqttClient = factory.CreateMqttClient();
  113.  
  114. var options = new MqttClientOptionsBuilder()
  115. .WithTcpServer(txtIp.Text, Convert.ToInt32(txtPort.Text)).WithCredentials(txtUsername.Text, txtPsw.Text).WithClientId(txtClientId.Text) // Port is optional
  116. .Build();
  117.  
  118. await mqttClient.ConnectAsync(options, CancellationToken.None);
  119. Invoke((new Action(() =>
  120. {
  121. txtReceiveMessage.AppendText($"连接到MQTT服务器成功!" + txtIp.Text);
  122. })));
  123. mqttClient.UseApplicationMessageReceivedHandler(e =>
  124. {
  125.  
  126. Invoke((new Action(() =>
  127. {
  128. txtReceiveMessage.AppendText($"收到订阅消息!" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
  129. })));
  130.  
  131. });
  132. }
  133. catch (Exception ex)
  134. {
  135.  
  136. Invoke((new Action(() =>
  137. {
  138. txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
  139. })));
  140. }
  141. }
  142. }
  143.  
  144. private void MqttClient_Connected(object sender, EventArgs e)
  145. {
  146. Invoke((new Action(() =>
  147. {
  148. txtReceiveMessage.Clear();
  149. txtReceiveMessage.AppendText("已连接到MQTT服务器!" + Environment.NewLine);
  150. })));
  151. }
  152.  
  153. private void MqttClient_Disconnected(object sender, EventArgs e)
  154. {
  155. Invoke((new Action(() =>
  156. {
  157. txtReceiveMessage.Clear();
  158. DateTime curTime = new DateTime();
  159. curTime = DateTime.UtcNow;
  160. txtReceiveMessage.AppendText($">> [{curTime.ToLongTimeString()}]");
  161. txtReceiveMessage.AppendText("已断开MQTT连接!" + Environment.NewLine);
  162. })));
  163.  
  164. //Reconnecting
  165. if (isReconnect)
  166. {
  167. Invoke((new Action(() =>
  168. {
  169. txtReceiveMessage.AppendText("正在尝试重新连接" + Environment.NewLine);
  170. })));
  171.  
  172. var options = new MqttClientOptionsBuilder()
  173. .WithClientId(txtClientId.Text)
  174. .WithTcpServer(txtIp.Text, Convert.ToInt32(txtPort.Text))
  175. .WithCredentials(txtUsername.Text, txtPsw.Text)
  176. //.WithTls()
  177. .WithCleanSession()
  178. .Build();
  179. Invoke((new Action(async () =>
  180. {
  181. await Task.Delay(TimeSpan.FromSeconds());
  182. try
  183. {
  184. await mqttClient.ConnectAsync(options);
  185. }
  186. catch
  187. {
  188. txtReceiveMessage.AppendText("### RECONNECTING FAILED ###" + Environment.NewLine);
  189. }
  190. })));
  191. }
  192. else
  193. {
  194. Invoke((new Action(() =>
  195. {
  196. txtReceiveMessage.AppendText("已下线!" + Environment.NewLine);
  197. })));
  198. }
  199. }
  200.  
  201. private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
  202. {
  203. Invoke((new Action(() =>
  204. {
  205. txtReceiveMessage.AppendText($">> {"### RECEIVED APPLICATION MESSAGE ###"}{Environment.NewLine}");
  206. })));
  207. Invoke((new Action(() =>
  208. {
  209. txtReceiveMessage.AppendText($">> Topic = {e.ApplicationMessage.Topic}{Environment.NewLine}");
  210. })));
  211. Invoke((new Action(() =>
  212. {
  213. txtReceiveMessage.AppendText($">> Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
  214. })));
  215. Invoke((new Action(() =>
  216. {
  217. txtReceiveMessage.AppendText($">> QoS = {e.ApplicationMessage.QualityOfServiceLevel}{Environment.NewLine}");
  218. })));
  219. Invoke((new Action(() =>
  220. {
  221. txtReceiveMessage.AppendText($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}");
  222. })));
  223. }
  224.  
  225. private void btnLogIn_Click(object sender, EventArgs e)
  226. {
  227. isReconnect = true;
  228. Task.Run(async () => { await ConnectMqttServerAsync(); });
  229. }
  230.  
  231. private void btnLogout_Click(object sender, EventArgs e)
  232. {
  233. isReconnect = false;
  234. Task.Run(async () => { await mqttClient.DisconnectAsync(); });
  235. }
  236.  
  237. }
  238. }

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. xLua下使用lua-protobuf

    本文发表于程序员刘宇的博客,转载请注明来源:https://www.cnblogs.com/xiaohutu/p/12168781.html protobuf作为一种通用套接字格式,各种插件里,最本质 ...

  2. Mysql 8+ 版本完全踩坑记录

    问题是这样 刚霍霍了一台腾讯云服务器需要安装mysql 然后就选择了8+这个版本. 安装步骤网上有的是. 我只写最主要的部分 绝对不出错 外网可访问 .net java都可以调用 其实不指望有人看 就 ...

  3. 关于selenium无法在chrome中自动播放flash的问题

    最近用selenium写个小脚本,遇到flash不能自动播放问题 我遇到的情况,直接提示 请确认是否安装flash,其实已经安装,点击下载flash,然后提示是否允许. 整了好久,发现终极方法: ## ...

  4. (转) exp1-1:// 一次有趣的XSS漏洞挖掘分析(1)

    from http://www.cnblogs.com/hookjoy/p/3503786.html 一次有趣的XSS漏洞挖掘分析(1)   最近认识了个新朋友,天天找我搞XSS.搞了三天,感觉这一套 ...

  5. IO系统-标准C的I/O和文件I/O

    1.标准C的I/O 1.1常用函数和结构体 char *fgets(char *s, int size, FILE *stream); //整行输入 int printf(const char *fo ...

  6. STVP编译时遇到no default placement for segment .FLASH_CODE

    最近编译STM8S003时需要使用flash库函数,看起来简单,实则折腾了超过1天.今天总结方法如下: 1.修改stm8s.h 156行  #define RAM_EXECUTION  注释去掉  如 ...

  7. JDK源码之String类解析

    一 概述 String由final修饰,是不可变类,即String对象也是不可变对象.这意味着当修改一个String对象的内容时,JVM不会改变原来的对象,而是生成一个新的String对象 主要考虑以 ...

  8. Redis 面试题汇总

    Redis 面试题汇总 1.Redis 使用场景有哪些? 答:Redis 使用场景如下: 记录帖子点赞数.点击数.评论数 缓存近期热帖 缓存文章详情信息 记录用户会话信息 2.Redis 有哪些功能? ...

  9. 按照相应的格式获取系统时间并将其转化为SQL中匹配的(date)时间格式

    在获取时间时需要对时间格式进行设置,此时就需要用到SimpleDateFormat 类 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM ...

  10. ATL的GUI程序设计(2)

    from:http://blog.titilima.com/atlgui-2.html 第二章 一个最简单窗口程序的转型 我知道,可能会有很多朋友对上一章的"Hello, World!&qu ...