我很想知道 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 服务器?