我有以下代码用于mqtt客户端从代理接收消息。如果客户端与broker断开连接,则客户端再次尝试使用connect()调用与broker连接。我读过paho文档,说loop_start()将处理与broker的重新连接。请让我知道使用connect() call与broker重新连接或让它自己处理是否正确。
import paho.mqtt.client as mqtt
import json
import time
is_connect = False
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print("Message received on "+msg.topic)
parsed_message = json.loads(msg.payload)
print(json.dumps(parsed_message, indent=4, sort_keys=True))
def on_disconnect(client, userdata, rc):
if rc != 0:
print "Unexpected disconnection." , (rc)
global is_connect
is_connect = False
while True:
global is_connect
#If client is not connected, initiate connection again
if not is_connect:
try:
client = mqtt.Client(client_id='testing_purpose', clean_session=False)
client.loop_stop()
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.connect("localhost", 1883, 5)
is_connect = True
client.loop_start()
time.sleep(15)
except Exception as err:
is_connect = False
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
#client.loop_forever()发布于 2017-10-16 22:18:06
好的,所以只有在您使用loop_forever函数时,Paho客户端才会重新连接。
因此,如果您想控制网络循环,您可以随时使用reconnect函数重新连接,而不是断开整个连接。但最简单的方法是只使用loop_forever函数,如下所示:
import paho.mqtt.client as mqtt
import json
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print("Message received on "+msg.topic)
parsed_message = json.loads(msg.payload)
print(json.dumps(parsed_message, indent=4, sort_keys=True))
def on_disconnect(client, userdata, rc):
if rc != 0:
print "Unexpected disconnection." , (rc)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client = mqtt.Client(client_id='testing_purpose', clean_session=False)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.loop_forever()https://stackoverflow.com/questions/46752888
复制相似问题