MQTT 客户端应用及常见问题(C#)
https://blog.csdn.net/dengyaan/article/details/51752327
最近因为工作需要,需要使用C# 语言编写一个通过MQTT协议 ,上传数据到云端的工具。因为之前没有用过MQTT,所以 使用的时候遇到很多问题.下面将会把我遇到的问题一一解释。
1.引用源码库地址
https://github.com/eclipse/paho.mqtt.m2mqtt
2.说明
https://m2mqtt.wordpress.com/m2mqtt_doc/
3.使用后遇到的问题
当网络中断后,MQTT 程序有时候不会自动重连。
解决方案 添加监控MQTT连接状态
1.添加全局静态变量 uPLibrary.Networking.M2Mqtt.MQTTConfig.IsSocketRun;
class MQTTConfig{
public static bool IsSocketRun = false;
}
1
2
3
2.修改MqttClient 类 的Connect 方法,在连接成功后把IsSocketRun = true.
MQTTConfig.IsSocketRun = true;
/// <summary>
/// Connect to broker
/// </summary>
/// <param name="clientId">Client identifier</param>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <param name="willRetain">Will retain flag</param>
/// <param name="willQosLevel">Will QOS level</param>
/// <param name="willFlag">Will flag</param>
/// <param name="willTopic">Will topic</param>
/// <param name="willMessage">Will message</param>
/// <param name="cleanSession">Clean sessione flag</param>
/// <param name="keepAlivePeriod">Keep alive period</param>
/// <returns>Return code of CONNACK message from broker</returns>
public byte Connect(string clientId,
string username,
string password,
bool willRetain,
byte willQosLevel,
bool willFlag,
string willTopic,
string willMessage,
bool cleanSession,
ushort keepAlivePeriod)
{
// create CONNECT message
MqttMsgConnect connect = new MqttMsgConnect(clientId,
username,
password,
willRetain,
willQosLevel,
willFlag,
willTopic,
willMessage,
cleanSession,
keepAlivePeriod,
(byte)this.ProtocolVersion);
try
{
// connect to the broker
this.channel.Connect();
}
catch (Exception ex)
{
throw new MqttConnectionException("Exception connecting to the broker", ex);
}
this.lastCommTime = 0;
this.isRunning = true;
MQTTConfig.IsSocketRun = true;
this.isConnectionClosing = false;
// start thread for receiving messages from broker
Fx.StartThread(this.ReceiveThread);
....
3.继续修改 MqttClient .cs类中的Ping() 方法
/// <summary>
/// Execute ping to broker for keep alive
/// </summary>
/// <returns>PINGRESP message from broker</returns>
private MqttMsgPingResp Ping()
{
MqttMsgPingReq pingreq = new MqttMsgPingReq();
try
{
// broker must send PINGRESP within timeout equal to keep alive period
return (MqttMsgPingResp)this.SendReceive(pingreq, this.keepAlivePeriod);
}
catch (Exception e)
{
#if TRACE
MqttUtility.Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", e.ToString());
#endif
MQTTConfig.IsSocketRun = false;
// client must close connection
this.OnConnectionClosing();
return null;
}
}
4.最后在我们程序集入口初始化程序的时候 添加线程调用 。当MQTT中断后就会自动重连 ,另外提醒方法异常时一定要异常处理哦。
while (true)
{
LogWriter.DebugLog(string.Format("执行次数{0} IsSocketRun {1}", i, uPLibrary.Networking.M2Mqtt.MQTTConfig.IsSocketRun));
if (!uPLibrary.Networking.M2Mqtt.MQTTConfig.IsSocketRun)
{
程序执行到吗。。。
}
System.Threading.Thread.Sleep(10000);
}
MQTT 订阅
// create client instance
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));
// register to message received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
// subscribe to the topic "/home/temperature" with QoS 2
client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
...
static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
// handle message received
}
MQTT 发布
…
// create client instance
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));
string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
string strValue = Convert.ToString(value);
// publish a message on "/home/temperature" topic with QoS 2
client.Publish("/home/temperature", Encoding.UTF8.GetBytes(strValue), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
...
---------------------
作者:dengyaan
来源:CSDN
原文:https://blog.csdn.net/dengyaan/article/details/51752327
版权声明:本文为博主原创文章,转载请附上博文链接!
MQTT 客户端应用及常见问题(C#)的更多相关文章
- MQTT Client library for C (MQTT客户端C语言库-paho)
原文:http://www.eclipse.org/paho/files/mqttdoc/MQTTClient/html/index.html 来自我的CSDN博客 最近在使用Paho的MQTT客 ...
- MQTT客户端库-Paho GO
为了加深理解,本文是翻译文章.原文地址 Paho GO Client 语言 GO 协议 EPL AND EDL 官网地址 http://www.eclipse.org/paho/ API类型 As ...
- linux c MQTT客户端实现
linux c MQTT客户端实现 摘自:https://www.jianshu.com/p/d309de966379 一.前言:mqtt协议是轻量级的消息订阅和发布(publish/subscrib ...
- MQTT客户端
MQTT客户端 最近公司项目中使用到了一个MQTT的协议,用这个通讯协议将嵌入式端收集到的数据接入到物联网中,很是方便的解决了,嵌入式端存储空间小,也解决了用户需要自定义使用这些记录数据的需求.而且相 ...
- 物联网架构成长之路(32)-SpringBoot集成MQTT客户端
一.前言 这里虽然是说MQTT客户端.其实对于服务器来说,这里的一个具有超级权限的MQTT客户端,就可以做很多事情.比如手机APP或者网页或者第三方服务需要发送数据到设备,但是这些又不是设备,又不能让 ...
- (二)MQTT客户端模拟连接阿里云并上传数据
本文主要讲述使用MQTT.fx接入物联网平台 一.下载MQTT.fx客户端 官网链接 二.设置相关参数 打开MQTT单片机编程工具,将三元组复制进去,生成所需要的信息 单片机工具下载地址 三元组还记得 ...
- Windows Server 2008 R2 添加且制成“NFS服务器”角色后与Unix客户端匿名访问常见问题
在复杂的主机与网络环境中,我们可能会接触到多种主机与操作系统,配合Windows Server 2008 R2的原生“NFS服务器”功能可以让这样的复杂操作系统更方便应用. 然而面对网络上众多的帮助指 ...
- MQTT客户端与服务代理的案列
服务端,采用 Mosquitto 来转发分发消息. 客户端自己写. 服务端 启动 mosquitto (底下的命令是我自己放到环境变量里面的,通过alias 运行mosquitto) Ishallbe ...
- 树莓派MQTT客户端搭建
树莓派安装和实现MQTT协议 下载Mosquitto 更新软件源:sudo apt-get update 下载g++编译器:sudo apt-get install g++ 安装:sudo apt- ...
随机推荐
- c# IComparable与IComparer接口
- Wireshark 分析Linux SSh 远程登录延迟问题
1.PuTTy远程登录延迟的分析 现象问题描述:在使用kali linux 的时候喜欢在后台运行而在Windows主机系统上安装PuTTY来实现远程登录 发现每次输入密码的时候会存在延迟10s的情况, ...
- Android GOT Hook
最后介绍的这种hook方式原理比较简单,只需要将GOT表中的目标函数地址替换为我们自己的函数地址即可,但它的缺点是只能对导入函数进行hook,还需要对elf文件的结构有所了解. 一.获取到GOT表在内 ...
- 文件操作之stat()函数
作用: 返回一个文件的详细信息 头文件: #include <sys/types.h> #include <sys/stat.h> #include <unistd.h& ...
- Python高级编程和异步IO并发编程(笔记)
一.魔法函数 # 例子 class Company(object): def __init__(self, employee_list): self.employee = employee_list ...
- drf框架 - 序列化组件 | Serializer
序列化组件 知识点:Serializer(偏底层).ModelSerializer(重点).ListModelSerializer(辅助群改) 序列化与反序列化 序列化: 将对象序列化成字符串用户传输 ...
- Oracle中日期作为条件的查询
1.范围日期的查询: select * from goods where g_time betweento_date('2018/12/26 10:01:59','yyyy-MM-dd hh:mi:s ...
- Flume拦截器、监控器
一.拦截器 1.拦截器:拦截器主要作用在source和channel之间,用于给event设置header消息头,如果没有设置拦截器,则event中只有message. 常见的拦截器有: Timest ...
- js原型和原型链的问题
<script> //js原型和原型链的概念 functionperson(name){ this.name=name; } person.prototype.age=18; person ...
- D. Vasya and Triangle(思维, 三角形)
传送门 题意: 给你 n, m, k, 问你是否存在一个三角形, 满足三角形的面积等于 n * m / k: 若存在, 输出YES, 且输出满足条件的三角形的三个坐标(答案有多种,则输出任意一种) ...