MQTT 06 - MQTT 客户端自动重连机制

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.

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jackindata

多谢认可!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值