【发布时间】:2018-03-26 22:42:17
【问题描述】:
我有下面的 mqtt 客户端代码,用于从代理接收消息。
如果客户端与代理断开连接,则客户端尝试再次使用connect() 调用与代理连接。我已阅读 paho 文档说 loop_start() 将处理与经纪人的重新连接。请让我知道是否可以使用connect() 呼叫与经纪人重新连接或让loop_start() 自己处理。
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()
【问题讨论】:
-
这里没有真正的问题。你试过这段代码看看会发生什么吗?
-
话虽如此,您可能希望将
is_connect = True移动到on_connect方法中 -
@hardillb 此代码工作正常。但是我怀疑我在每次断开连接时都在创建 mqtt 客户端的对象。这样做会与 mqtt 代理产生任何问题。我也将 is_connect = True 移动到 on_connect()
标签: python python-2.7 mqtt paho