无法在 Python 脚本中的无限循环中发布 MQTT 服务器

物联网 MQTT 帕霍 Python
2021-06-01 09:30:01

我很想知道 MQTT 服务器的性能如何。所以我创建了这个 Python 脚本:

import time
import paho.mqtt.client as mqtt
from multiprocessing import Pool


def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    client.subscribe("test")
    while True:
        client.publish("test","hello world")


def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("myserver.example.com", 1883, 60)
client.loop_forever()

当我使用 运行此脚本时python3 myscript.py,终端会停止并显示此消息Connected with result code 0

当我摆脱 while 循环并执行以下操作时:

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    client.subscribe("test")
    client.publish("test","hello world")
    client.publish("test","hello world")
    client.publish("test","hello world")
    ... print this another 20 times ...

一切正常。我什至可以从订阅了 MQTT 服务器的另一个客户端设备接收此消息。如果我将client.publish无限循环放入内部,事情只会停止工作我还尝试在 while 循环中使用异步调用,并尝试在 while 循环中放置一个 time.sleep(),但这仍然没有变化----也就是说,while 循环仍然挂起。

我究竟做错了什么?如何让我的 Python 脚本持续发布到 MQTT 服务器?

1个回答

您不应该在回调中长时间运行(无限循环)。

所有回调都在客户端网络线程的主循环(由 启动的那个client.loop_forever())上运行。

这意味着如果on_connect()线程永远不会返回,它将永远无法处理client.publish()循环中的调用

单个client.publish()调用有效,因为您建立了一个要发布的消息队列,然后on_connect()返回和线程可以处理该积压。

PS 你的微基准不太可能给出真实的结果,但如果你真的想运行它,你可以尝试:

import paho.mqtt.client as mqtt
 
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("test")


def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("myserver.example.com", 1883, 60)
while True:
    client.publish("test","hello world")
    client.loop()