我有以下代码用于mqtt客户端从代理接收消息。
如果客户端与代理断开连接,则客户端会再次使用<p>This is some text<span>foo</span><span>bar</span></p>
调用尝试与代理连接。我读过paho文档,说connect()
将处理与经纪人的重新连接。如果使用loop_start()
调用与代理重新连接或由connect()
本身处理它是否正确,请告诉我。
loop_start()
答案 0 :(得分:0)
好的,所以如果你使用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()