mqtt 传文件断开连接的原因_Paho MQTT客户端连接可靠性(断开连接时重新连接)...

What is the most reliable way to use the Python Paho MQTT client? I want to be able to handle connection interruptions due to WiFi drops and keep trying to reconnect until it's successful.

What I have is the following, but are there any best practices I'm not adhering to?

import argparse

from time import sleep

import paho.mqtt.client as mqtt

SUB_TOPICS = ("topic/something", "topic/something_else")

RECONNECT_DELAY_SECS = 2

def on_connect(client, userdata, flags, rc):

print "Connected with result code %s" % rc

for topic in SUB_TOPICS:

client.subscribe(topic)

# EDIT: I've removed this function because the library handles

# reconnection on its own anyway.

# def on_disconnect(client, userdata, rc):

# print "Disconnected from MQTT server with code: %s" % rc

# while rc != 0:

# sleep(RECONNECT_DELAY_SECS)

# print "Reconnecting..."

# rc = client.reconnect()

def on_msg(client, userdata, msg):

print "%s %s" % (msg.topic, msg.payload)

if __name__ == "__main__":

p = argparse.ArgumentParser()

p.add_argument("user")

p.add_argument("password")

p.add_argument("host")

p.add_argument("--port", type=int, default=1883)

args = p.parse_args()

client = mqtt.Client()

client.on_connect = on_connect

client.on_message = on_msg

client.username_pw_set(args.user, args.password)

client.connect(args.host, args.port, 60)

client.loop_start()

try:

while True:

sleep(1)

except KeyboardInterrupt:

pass

finally:

client.loop_stop()

解决方案Set a client_id so it's the same across reconnects

Set the clean_session=false connection option

Subscribe at QOS greater than 0

These options will help ensure that any messages published while disconnected will be delivered once the connection is restored.

You can set the client_id and clean_session flag in the constructor

client = mqtt.Client(client_id="foo123", clean_session=False)

And set the QOS of the subscription after the topic

client.subscribe(topic, qos=1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值