Python Paho client publish failures with at least

2019-05-21 10:39发布

问题:

I am writing a python client using paho-mqtt, I use publish() to publish data using established connection.

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

But the server will time me out. However, I do not get the timeout until I call publish again.

I got rc in the order of:

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

Using Wireshark, I see that as I publish the 2nd time, the connection is reset. But I don't get the "Broken pipe" until my 3rd publish. I tried supplying on_disconnect callback and it is also only called after 3rd publish.

What is the right way to call publish and be notified that the publish has failed immediately? Also, the "Broken pipe" message does not appear to be an exception. How do I prevent it from printing?

回答1:

As hinted at by @jan-vlcinsky you need to include a call to either start the client network loop in the background or run the loop in the foreground.

E.g.

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

Or

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


标签: python mqtt paho