码迷,mamicode.com
首页 > 其他好文 > 详细

MQTT 客户端自动重连机制

时间:2018-08-22 16:53:28      阅读:2855      评论:0      收藏:0      [点我收藏+]

标签:rev   his   flag   data   对象   事件   _for   提示   sub   

Paho 客户端的 python 实现:
https://pypi.org/project/paho-mqtt/

进入 client 的事件循环之后,Paho client 内部将会自动处理掉线重连。但是重连后的状态变化,重连的重试次数等,需要小心处理。


以下几个参数与函数接口需要特别留意。

  • loop_start()、loop_forever() 接口进入 client 事件循环,此时开始将自动处理掉线重连的问题。

It automatically handles reconnecting.

  • Client 对象构造的参数 clean_session,默认为 True,在重连后,该 client 在 broker 的状态将会被清除。

a boolean that determines the client type. If True, the broker will remove all information about this client when it disconnects. If False, the client is a durable client and subscription information and queued messages will be retained when the client disconnects.Note that a client will never discard its own outgoing messages on disconnect. Calling connect() or reconnect() will cause the messages to be resent. Use reinitialise() to reset a client to its original state.

  • reconnect_delay_set(min_delay=1, max_delay=120) 接口决定掉线重连时的重试次数,在网络较差的情况下不妨把 max 值设置大一点。

The client will automatically retry connection. Between each attempt it will wait a number of seconds between min_delay and max_delay.
When the connection is lost, initially the reconnection attempt is delayed of min_delay seconds. It’s doubled between subsequent attempt up to max_delay.

  • on_connect(client, userdata, flags, rc) 回调中的 flags 参数也需要注意,他提示了此时 broker 中是否还保留有 client 先前相关信息。如果前面的 clean_session 设置为 True 的话,这个 flags 不用理会。否则,就要考虑重新订阅相应的主题等问题了。

using clean session set to 0 only. If a client with clean session=0, that reconnects to a broker that it has previously connected to, this flag indicates whether the broker still has the session information for the client. If 1, the session still exists.

MQTT 客户端自动重连机制

标签:rev   his   flag   data   对象   事件   _for   提示   sub   

原文地址:https://www.cnblogs.com/liaojieliang/p/mqtt-paho-reconnect.html

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!