Python Paho 客户端发布失败,至少错过了 1 次发布

Python Paho client publish failures with at least 1 missed publsh

我正在使用 paho-mqtt 编写 python 客户端,我使用 publish() 来使用已建立的连接发布数据。

mqttc = mqtt.Client()
...
while True:
    ...
    rc = mqttc.publish(topic, data)

但是服务器会让我超时。但是,在我再次调用发布之前,我不会超时。

我得到 rc 的顺序是:

(0, 1)
delay
(0, 2)
[Errno 32] Broken pipe
(1, 3)

使用 Wireshark,我发现当我第二次发布时,连接被重置。但是直到我第三次发布时我才得到 "Broken pipe"。我尝试提供 on_disconnect 回调,它也仅在第 3 次发布后调用。

调用发布并立即收到发布失败通知的正确方法是什么?此外,"Broken pipe" 消息似乎也不例外。如何防止打印?

正如@jan-vlcinsky 所暗示的,您需要包含一个调用以在后台启动客户端网络循环或运行 在前台启动循环。

例如

mqttc = mqtt.Client()
mqttc.loop_start()
...
while True:
    ...
    rc = mqttc.publish(topic, data)

mqttc = mqtt.Client()
...
while True:
    ...
    rc = mqttc.publish(topic, data)
    mqttc.loop()