MQTT Broker没有按时交付发布者发送的消息



我编写了这个MQTT发布者代码:

import paho.mqtt.client as mqtt
import time
HOST = "localhost"
PORT = 1883
KEEP_ALIVE_INT = 100
TOPIC = "noti"
def sendMsg():
MSG = ["1111",  "2222", "3333", "4444", "5555"]
i = 0
try:
while i<5:
client.publish(TOPIC, MSG[i], qos=0)
i+=1
time.sleep(1)
except Exception as e:
print("Caught Exception: " + e)
def onConnect(client, userdata, flags, rc):
if rc == 0:
print("Connected successfully")
sendMsg()
else:
print("Connection failed, result code: " + str(rc))
def onPublish(client, userdata, mid):
print ("Message is published")
client = mqtt.Client("pub")
client.on_connect = onConnect
client.on_publish = onPublish
client.connect(HOST, PORT, KEEP_ALIVE_INT)
client.loop_forever()

并且,以下是MQTT订阅者代码:

import paho.mqtt.client as mqtt
import time
HOST = "localhost"
PORT = 1883
KEEP_ALIVE_INT = 100
TOPIC = "noti"
def onConnect(client, userdata, flags, rc):
if rc == 0:
print("=> Connected successfully")
client.subscribe(TOPIC, 0)
else:
print("=> Connection failed, result code: " + str(rc))

def onSubscribe(mosq, obj, mid, granted_qos):
print ("=> Subscribed to topic: " + TOPIC)
print ("Granted QOS: "+str(granted_qos))

def onMessage(client, userdata, msg):
print("=> Received message: " + msg.topic +" - " + msg.payload.decode("utf-8"))

client = mqtt.Client("sub")
client.on_message = onMessage
client.on_connect = onConnect
client.on_subscribe = onSubscribe
client.connect(HOST, PORT, KEEP_ALIVE_INT )
client.loop_forever()

我在我的电脑上使用蚊子代理。

每1秒发布一次,但是我可以看到print "Message是published"在所有5条消息发布后,执行5次。此外,订阅者在5秒后一起接收消息,而不是每1秒接收一次。

请帮我理解这个错误,建议修改。

这是因为所有回调和消息处理都发生在客户端网络循环线程上,而您通过不从on_connect()回调返回来阻塞该线程。

所以对client.publish()的调用排队,直到on_connect()回调返回。

您需要找到一种不在客户端循环上触发sendMsg()函数的方法。(可能在一个单独的线程上)

相关内容

  • 没有找到相关文章