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#)的更多相关文章

  1. MQTT Client library for C (MQTT客户端C语言库-paho)

    原文:http://www.eclipse.org/paho/files/mqttdoc/MQTTClient/html/index.html 来自我的CSDN博客   最近在使用Paho的MQTT客 ...

  2. MQTT客户端库-Paho GO

    为了加深理解,本文是翻译文章.原文地址 Paho GO Client   语言 GO 协议 EPL AND EDL 官网地址 http://www.eclipse.org/paho/ API类型 As ...

  3. linux c MQTT客户端实现

    linux c MQTT客户端实现 摘自:https://www.jianshu.com/p/d309de966379 一.前言:mqtt协议是轻量级的消息订阅和发布(publish/subscrib ...

  4. MQTT客户端

    MQTT客户端 最近公司项目中使用到了一个MQTT的协议,用这个通讯协议将嵌入式端收集到的数据接入到物联网中,很是方便的解决了,嵌入式端存储空间小,也解决了用户需要自定义使用这些记录数据的需求.而且相 ...

  5. 物联网架构成长之路(32)-SpringBoot集成MQTT客户端

    一.前言 这里虽然是说MQTT客户端.其实对于服务器来说,这里的一个具有超级权限的MQTT客户端,就可以做很多事情.比如手机APP或者网页或者第三方服务需要发送数据到设备,但是这些又不是设备,又不能让 ...

  6. (二)MQTT客户端模拟连接阿里云并上传数据

    本文主要讲述使用MQTT.fx接入物联网平台 一.下载MQTT.fx客户端 官网链接 二.设置相关参数 打开MQTT单片机编程工具,将三元组复制进去,生成所需要的信息 单片机工具下载地址 三元组还记得 ...

  7. Windows Server 2008 R2 添加且制成“NFS服务器”角色后与Unix客户端匿名访问常见问题

    在复杂的主机与网络环境中,我们可能会接触到多种主机与操作系统,配合Windows Server 2008 R2的原生“NFS服务器”功能可以让这样的复杂操作系统更方便应用. 然而面对网络上众多的帮助指 ...

  8. MQTT客户端与服务代理的案列

    服务端,采用 Mosquitto 来转发分发消息. 客户端自己写. 服务端 启动 mosquitto (底下的命令是我自己放到环境变量里面的,通过alias 运行mosquitto) Ishallbe ...

  9. 树莓派MQTT客户端搭建

    树莓派安装和实现MQTT协议 下载Mosquitto 更新软件源:sudo apt-get  update 下载g++编译器:sudo apt-get install g++ 安装:sudo apt- ...

随机推荐

  1. PyQt5入门

    PyQt5 是用来创建Python GUI应用程序的工具包.作为一个跨平台的工具包,PyQt可以在所有主流操作系统上运行(Unix,Windows,Mac). 本文描述Windows系统下如何安装Py ...

  2. Educational Codeforces Round 71 (Rated for Div. 2)-F. Remainder Problem-技巧分块

    Educational Codeforces Round 71 (Rated for Div. 2)-F. Remainder Problem-技巧分块 [Problem Description] ​ ...

  3. 在linux上搭建SVN服务器并自动更新至WEB目录

    1.仓库放在 /var/svn/ 目录下,并且仓库名为 project 2.创建用户组user,该组下添加两个成员user1.user2,密码直接用用户名,两用户可以checkout代码和提交代码 3 ...

  4. 使用React.Fragment替代render函数中div的包裹

    1.在 React 中,render 函数中 return 的内容只能有一个根节点,如果多个元素嵌套,需要用一个标签元素包裹 这个包裹的标签通常用 div,示例如下: class App extend ...

  5. WPF + SelfHost 实现窗体自宿主(API,API和窗体通信)

    前言 今天研究了在 WPF 中使用 SelfHost 自宿主. 具体的功能是,在 WPF 中使用自宿主服务,外部调用服务的 API,在 API 里面操作窗体的显示等. 技术点 在 WPF 中集成 Se ...

  6. 创建型模式(过渡模式) 简单工厂模式(Simple Factory)

    简单工厂模式(Simple Factory Pattern)属于类的创建型模式,又叫静态工厂方法模式(Static FactoryMethod Pattern) 是通过专门定义一个类来负责创建其他类的 ...

  7. 2019CCPC网络赛 HDU 6702——找规律

    题意 给定 $A,B$(都是正整数),求使得 $(A\  xor\  C) \& (B \ xor \  C)$ 最小的正整数 $C$,如果有多个满足条件的 $C$,输出最小的 $C$. 分析 ...

  8. netty: 解决粘包拆包: 分隔符DelimiterBasedFrameDecoder,定长消息FixedLengthFrameDecoder

    DelimiterBasedFrameDecoder 自定义分隔符 给Server发送多条信息,但是server会讲多条信息合并为一条.这时候我们需要对发生的消息指定分割,让client和server ...

  9. WinDbg常用命令系列---查看线程调用栈命令K*简介

    Windbg里的K*命令显示给定线程的堆栈帧以及相关信息,对于我们调试时,进行调用栈回溯有很大的帮助. 一.K*命令使用方式 在不同平台上,K*命令的使用组合如下 User-Mode, x86 Pro ...

  10. Linux下安装Phalcon系统环境安装Phalcon 及 安装Phalcon Developer Tools

    一.安装Phalcon Phalcon 需要用的的PHP扩展函数有如下: curl gettext gd2 (to use the Phalcon\Image\Adapter\Gd class) li ...