paho mqtt(python)-loop_start()不起作用
我正在编写一个仅连接到经纪人,发布消息然后断开连接的MQTT客户端。这是代码:
def on_connect_v5(client, userdata, flags, rc, properties):
print('connected')
client.publish(topic, payload, 0)
def on_publish(client, userdata, mid):
print(f'mid: {mid}')
client.disconnect()
client = paho.Client(protocol=paho.MQTTv5)
client.on_connect = on_connect_v5
client.on_publish = on_publish
client.connect(host, port, 60)
client.loop_start()
# client.loop_forever()
问题是当我使用loop_start()
时,看来客户端没有成功连接,但是loop_forever()
可以使用。我是否在loop_start()
函数上做错了什么,使用它的正确方法是什么?
btw:尝试使用
paho.mqtt.publish
模块,并始终获得一个套接字计时。感谢是否也能解释它。
I'm writing a MQTT client which simply connects to the broker, publish a message and then disconnect. Here's the code:
def on_connect_v5(client, userdata, flags, rc, properties):
print('connected')
client.publish(topic, payload, 0)
def on_publish(client, userdata, mid):
print(f'mid: {mid}')
client.disconnect()
client = paho.Client(protocol=paho.MQTTv5)
client.on_connect = on_connect_v5
client.on_publish = on_publish
client.connect(host, port, 60)
client.loop_start()
# client.loop_forever()
The question is when I use loop_start()
, it seems the client isn't connected successfully, but loop_forever()
would work. Have I done something wrong with the loop_start()
function, and what's the proper way to use it?
BTW: have tried use the
paho.mqtt.publish
module and always get a Socket timed out. Appreciated if someone can explain it as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
区别在于
loop_forever
阻止程序。loop_start
,仅启动守护程序线程,但不会阻止。因此您的程序继续进行。在您显示的代码中,这意味着程序存在。您可以在此处阅读更多信息: https://github.com/eclipse/paho。 mqtt.python#Network-Loop
The difference is that
loop_forever
blocks the program.loop_start
, only starts a daemon thread, but doesn't block. So your program continues. In the code you show, this means the program exists.You can read more here: https://github.com/eclipse/paho.mqtt.python#network-loop
您的主线程不等待
loop_start()
;因为它的守护程序。在完成工作之前,守护程序线程不会阻止程序。当您的主线程完成时,您的工作就会自杀。那也是杀死您的loop_start()
线程。如果您的主线程具有无限循环或更长的循环,则您的loop_start()
正常工作Your main threads not waiting
loop_start()
; because its daemon thread. Daemon threads not block the program until finish its job. When your main thread done its your job kill itself. That's the also kill yourloop_start()
thread. If your main thread has infinite loop or longer loops, yourloop_start()
works perfectly