MQTT 客户端自动重连机制


Paho 客户端的 python 实现:

进入 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.

廖杰良 - 2018-8-22