MQTT Python客户端异常断开连接

时间:2018-07-09 11:51:36

标签: python mqtt

我写了基本的MQTT python-client。但是,它会不正确地断开连接而不会出现任何错误。当我查看事件日志文件时,我发现它已连接,同时不正常地断开了连接。

import paho.mqtt.client as mqtt

Broker = "192.168.43.246"

def on_connect(client, userdata, flages, rc):
        print("Connected with result code=",rc)

client = mqtt.Client(client_id="Client123", clean_session=False, userdata=None)
client.on_connect = on_connect
client.connect(Broker, 1883, 60)

在这里,我还附上了事件日志的快照。 event log

1 个答案:

答案 0 :(得分:0)

@MikeScotty的答案不正确。缺少的是启动MQTT网络循环。需要开始循环,以处理发送保持活动的数据包,对QoS 1/2消息进行多路握手以及处理传入订阅。

如果您只是想保持连接状态或10秒钟,那么类似的方法将起作用

import paho.mqtt.client as mqtt
import time

Broker = "192.168.43.246"

def on_connect(client, userdata, flages, rc):
        print("Connected with result code=",rc)

client = mqtt.Client(client_id="Client123", clean_session=False, userdata=None)
client.on_connect = on_connect
client.connect(Broker, 1883, 60)
client.loop_start() # starts network loop on separate thread
time.sleep(10) # optionally wait some time
client.disconnect() # disconnect gracefully
client.loop_stop() # stops network loop

如果您想永远保持连接(或直到被杀死),那么您有2个选择

...
client.connect(Broker, 1883, 60)
client.loop_forever()

这将在前台启动网络循环(并一直阻塞直到被杀死)。

...
client.connect(Broker, 1883, 60)
while True:
  client.loop() # runs one iteration of the network loop
  # do something else

...
client.connect(Broker, 1883, 60)
client.loop_start()
while True:
  # do something else