热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

【语言c#】MQTT订阅与发布

一、框架windows10.NETFramework4.6.1MQTTnet3.0.5.01、packages.config
一、框架

windows 10

.NETFramework 4.6.1

MQTTnet 3.0.5.0

1、packages.config



原始文档

NuGet包

二、工具

org.eclipse.paho.ui.app-1.0.2-win32.win32.x86_64.zip(jdk-8u211-windows-x64.exe)

遇到问题

Paho
A Java Runtime Environment(JRE)or Java Development Kit (JDK) 
must be available in order to run Paho. No Java virtual machine 
was found after searching the following location:
...\org.eclipse.paho.ui.app-1.0.2-win32.win32.x86_64\jre\bin\javaw.exe
Javaw.exe in your current Path

解决方案

安装 JDK 并设置环境变量 , 如:Windows 10 x64 安装 "jdk-8u211-windows-x64.exe"

jdk-8u211-windows-x64.exe 配置

JDK 安装路径举例如下,以实际安装为准:
InstallPath JDK : C:\Program Files\Java\jdk1.8.0_211
InstallPath JRE : C:\Program Files\Java\jre1.8.0_211[电脑-属性-高级系统设置-环境变量-系统变量]
1、添加
变量名:JAVA_HOME
变量值:C:\Program Files\Java\jdk1.8.0_211
2、添加
变量名:JRE_HOME
变量值:C:\Program Files\Java\jre1.8.0_211
3、添加
变量名:CLASSPATH
变量值:.;%JAVA_HOME%\lib;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;
4、追加
变量名:Path
变量值:;%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;

 

三、管理 NuGet 程序包 

方法一、VS2013>工具>NuGet包管理器>程序包管理器控制台


NETStandard.Library

Install-Package NETStandard.Library –Version 2.0.3

MQTTnet

Install-Package MQTTnet –Version 3.0.5

方法二、VS2013>解决方案资源管理器>[Project]>引用(右键)>管理NuGet程序包(N)...


NETStandard.Library

MQTTnet

四、编写订阅和发布代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Packets;
using MQTTnet.Protocol;
using MQTTnet.Client.Receiving;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Connecting;namespace CSDN
{class HOSMQTT{private static MqttClient mqttClient = null;private static IMqttClientOptions options = null;private static bool runState = false;private static bool running = false;///

/// 服务器IP/// private static string ServerUrl &#61; "182.61.51.85";/// /// 服务器端口/// private static int Port &#61; 61613;/// /// 选项 - 开启登录 - 密码/// private static string Password &#61; "ruichi8888";/// /// 选项 - 开启登录 - 用户名/// private static string UserId &#61; "admin";/// /// 主题/// China/Hunan/Yiyang/Nanxian/// Hotel/Room01/Tv/// Hospital/Dept01/Room001/Bed001/// Hospital/#/// private static string Topic &#61; "China/Hunan/Yiyang/Nanxian";/// /// 保留/// private static bool Retained &#61; false;/// /// 服务质量/// 0 - 至多一次/// 1 - 至少一次/// 2 - 刚好一次/// private static int QualityOfServiceLevel &#61; 0;public static void Stop(){runState &#61; false;}public static bool IsRun(){return (runState && running);}/// /// 启动客户端/// public static void Start(){try{runState &#61; true;System.Threading.Thread thread &#61; new System.Threading.Thread(new System.Threading.ThreadStart(Work));thread.Start();}catch (Exception exp){Console.WriteLine(exp);}}/// /// /// private static void Work(){running &#61; true;Console.WriteLine("Work >>Begin");try{var factory &#61; new MqttFactory();mqttClient &#61; factory.CreateMqttClient() as MqttClient;options &#61; new MqttClientOptionsBuilder().WithTcpServer(ServerUrl, Port).WithCredentials(UserId, Password).WithClientId(Guid.NewGuid().ToString().Substring(0, 5)).Build();mqttClient.ConnectAsync(options);mqttClient.ConnectedHandler &#61; new MqttClientConnectedHandlerDelegate(new Func(Connected));mqttClient.DisconnectedHandler &#61; new MqttClientDisconnectedHandlerDelegate(new Func(Disconnected));mqttClient.ApplicationMessageReceivedHandler &#61; new MqttApplicationMessageReceivedHandlerDelegate(new Action(MqttApplicationMessageReceived));while (runState){System.Threading.Thread.Sleep(100);}}catch (Exception exp){Console.WriteLine(exp);}Console.WriteLine("Work >>End");running &#61; false;runState &#61; false;}public static void StartMain(){try{var factory &#61; new MqttFactory();var mqttClient &#61; factory.CreateMqttClient();var options &#61; new MqttClientOptionsBuilder().WithTcpServer(ServerUrl, Port).WithCredentials(UserId, Password).WithClientId(Guid.NewGuid().ToString().Substring(0, 5)).Build();mqttClient.ConnectAsync(options);mqttClient.UseConnectedHandler(async e &#61;>{Console.WriteLine("Connected >>Success");// Subscribe to a topicvar topicFilterBulder &#61; new TopicFilterBuilder().WithTopic(Topic).Build();await mqttClient.SubscribeAsync(topicFilterBulder);Console.WriteLine("Subscribe >>" &#43; Topic);});mqttClient.UseDisconnectedHandler(async e &#61;>{Console.WriteLine("Disconnected >>Disconnected Server");await Task.Delay(TimeSpan.FromSeconds(5));try{await mqttClient.ConnectAsync(options);}catch (Exception exp){Console.WriteLine("Disconnected >>Exception" &#43; exp.Message);}});mqttClient.UseApplicationMessageReceivedHandler(e &#61;>{Console.WriteLine("MessageReceived >>" &#43; Encoding.UTF8.GetString(e.ApplicationMessage.Payload));});Console.WriteLine(mqttClient.IsConnected.ToString());}catch (Exception exp){Console.WriteLine("MessageReceived >>" &#43; exp.Message);}}/// /// 发布/// /// 0 - 最多一次/// 1 - 至少一次/// 2 - 仅一次/// /// 发布主题/// 发布内容/// public static void Publish( string Topic,string Message){try{if (mqttClient &#61;&#61; null) return;if (mqttClient.IsConnected &#61;&#61; false)mqttClient.ConnectAsync(options);if (mqttClient.IsConnected &#61;&#61; false){Console.WriteLine("Publish >>Connected Failed! ");return;}Console.WriteLine("Publish >>Topic: " &#43; Topic &#43; "; QoS: " &#43; QualityOfServiceLevel &#43; "; Retained: " &#43; Retained &#43; ";");Console.WriteLine("Publish >>Message: " &#43; Message);MqttApplicationMessageBuilder mamb &#61; new MqttApplicationMessageBuilder().WithTopic(Topic).WithPayload(Message).WithRetainFlag(Retained);if (QualityOfServiceLevel &#61;&#61; 0){mamb &#61; mamb.WithAtMostOnceQoS();}else if (QualityOfServiceLevel &#61;&#61; 1){mamb &#61; mamb.WithAtLeastOnceQoS();}else if (QualityOfServiceLevel &#61;&#61; 2){mamb &#61; mamb.WithExactlyOnceQoS();}mqttClient.PublishAsync(mamb.Build());}catch (Exception exp){Console.WriteLine("Publish >>" &#43; exp.Message);}}/// /// 连接服务器并按标题订阅内容/// /// /// private static async Task Connected(MqttClientConnectedEventArgs e){try{List listTopic &#61; new List();if (listTopic.Count() <&#61; 0){var topicFilterBulder &#61; new TopicFilterBuilder().WithTopic(Topic).Build();listTopic.Add(topicFilterBulder);Console.WriteLine("Connected >>Subscribe " &#43; Topic);}await mqttClient.SubscribeAsync(listTopic.ToArray());Console.WriteLine("Connected >>Subscribe Success");}catch (Exception exp){Console.WriteLine(exp.Message);}}/// /// 失去连接触发事件/// /// /// private static async Task Disconnected(MqttClientDisconnectedEventArgs e){try{Console.WriteLine("Disconnected >>Disconnected Server");await Task.Delay(TimeSpan.FromSeconds(5));try{await mqttClient.ConnectAsync(options);}catch (Exception exp){Console.WriteLine("Disconnected >>Exception " &#43; exp.Message);}}catch (Exception exp){Console.WriteLine(exp.Message);}}/// /// 接收消息触发事件/// /// private static void MqttApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e){try{string text &#61; Encoding.UTF8.GetString(e.ApplicationMessage.Payload);string Topic &#61; e.ApplicationMessage.Topic;string QoS &#61; e.ApplicationMessage.QualityOfServiceLevel.ToString();string Retained &#61; e.ApplicationMessage.Retain.ToString();Console.WriteLine("MessageReceived >>Topic:" &#43; Topic &#43; "; QoS: " &#43; QoS &#43; "; Retained: " &#43; Retained &#43; ";");Console.WriteLine("MessageReceived >>Msg: " &#43; text);}catch (Exception exp){Console.WriteLine(exp.Message);}}}
}

五、测试

1、启动

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace CSDN
{class Program{static void Main(string[] args){HOSMQTT.Start();}}
}

2、使用Paho 工具发布消息


设置服务器IP和端口

设置用户名密码

连接服务

发布消息

监控订阅结果

 

 

 


推荐阅读
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了如何使用C#制作Java+Mysql+Tomcat环境安装程序,实现一键式安装。通过将JDK、Mysql、Tomcat三者制作成一个安装包,解决了客户在安装软件时的复杂配置和繁琐问题,便于管理软件版本和系统集成。具体步骤包括配置JDK环境变量和安装Mysql服务,其中使用了MySQL Server 5.5社区版和my.ini文件。安装方法为通过命令行将目录转到mysql的bin目录下,执行mysqld --install MySQL5命令。 ... [详细]
  • IjustinheritedsomewebpageswhichusesMooTools.IneverusedMooTools.NowIneedtoaddsomef ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • eclipse学习(第三章:ssh中的Hibernate)——11.Hibernate的缓存(2级缓存,get和load)
    本文介绍了eclipse学习中的第三章内容,主要讲解了ssh中的Hibernate的缓存,包括2级缓存和get方法、load方法的区别。文章还涉及了项目实践和相关知识点的讲解。 ... [详细]
  • 关键词:Golang, Cookie, 跟踪位置, net/http/cookiejar, package main, golang.org/x/net/publicsuffix, io/ioutil, log, net/http, net/http/cookiejar ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • 闭包一直是Java社区中争论不断的话题,很多语言都支持闭包这个语言特性,闭包定义了一个依赖于外部环境的自由变量的函数,这个函数能够访问外部环境的变量。本文以JavaScript的一个闭包为例,介绍了闭包的定义和特性。 ... [详细]
  • 开发笔记:Java是如何读取和写入浏览器Cookies的
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Java是如何读取和写入浏览器Cookies的相关的知识,希望对你有一定的参考价值。首先我 ... [详细]
  • web.py开发web 第八章 Formalchemy 服务端验证方法
    本文介绍了在web.py开发中使用Formalchemy进行服务端表单数据验证的方法。以User表单为例,详细说明了对各字段的验证要求,包括必填、长度限制、唯一性等。同时介绍了如何自定义验证方法来实现验证唯一性和两个密码是否相等的功能。该文提供了相关代码示例。 ... [详细]
  • Java自带的观察者模式及实现方法详解
    本文介绍了Java自带的观察者模式,包括Observer和Observable对象的定义和使用方法。通过添加观察者和设置内部标志位,当被观察者中的事件发生变化时,通知观察者对象并执行相应的操作。实现观察者模式非常简单,只需继承Observable类和实现Observer接口即可。详情请参考Java官方api文档。 ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
author-avatar
阮三岁
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有