【问题标题】:MQTT Broker does not deliver the messages sent by publisher, on timeMQTT Broker 没有按时传递发布者发送的消息
【发布时间】:2021-10-30 06:37:02
【问题描述】:

我编写了这个 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()

我在我的 PC 中使用 Mosquitto 代理。

每 1 秒发布一次,但在所有 5 条消息都发布后,我可以看到 5 次打印“消息已发布”。此外,订阅者会在 5 秒后一起接收消息,而不是每 1 秒一次。

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

【问题讨论】:

  • 打印收到的消息时添加时间戳。这将让您了解您是在 5 秒后收到消息,还是在 5 秒后才看到消息。

标签: mqtt mosquitto paho


【解决方案1】:

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

所以对client.publish() 的调用会排队等待on_connect() 回调返回。

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

【讨论】:

  • 谢谢@hardillb,你的建议奏效了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多