MQTT 订阅不起作用

物联网 MQTT 帕霍
2021-06-08 06:52:35

我正在努力通过 MQTT 代理将我的服务器连接到客户端。MQTT 客户端已连接。但是在发布消息后,订阅代码会收到一个连接确认。on_message() 函数永远不会被调用。

我被困在这里。

我已经粘贴了订阅客户端代码和输出。

import paho.mqtt.client as paho
import time

client = paho.Client("local_test")
topic = "topic_1"

def on_log(client, userdata, level, buff):  # mqtt logs function
    print(buff)

def on_connect(client, userdata, flags, rc):  # connect to mqtt broker function
    if rc == 0:
        client.connected_flag = True  # set flags
        print("Connected Info")
    else:
        print("Bad connection returned code = " + str(rc))
        client.loop_stop()

def on_disconnect(client, userdata, rc):  # disconnect to mqtt broker function
    print("Client disconnected OK")

def on_publish(client, userdata, mid):  # publish to mqtt broker
    print("In on_pub callback mid=" + str(mid))

def on_subscribe(client, userdata, mid, granted_qos):  # subscribe to mqtt broker
    print("Subscribed", userdata)

def on_message(client, userdata, message):  # get message from mqtt broker 
    print("New message received: ", str(message.payload.decode("utf-8")), "Topic : %s ", message.topic, "Retained : %s", message.retain)

def connectToMqtt():  # connect to MQTT broker main function
    print("Connecting to MQTT broker")
    client.username_pw_set(username=user, password=passwd)
    client.on_log = on_log
    client.on_connect = on_connect
    client.on_publish = on_publish
    client.on_subscribe = on_subscribe
    client.connect(broker, port, keepalive=600)
    ret = client.subscribe(topic, qos=0)
    print("Subscribed return = " + str(ret))
    client.on_message = on_message

connectToMqtt()  # connect to mqtt broker
client.loop_forever()

在同一主题上发布消息后我得到的输出是:

Connecting to MQTT broker
Sending CONNECT (u1, p1, wr0, wq0, wf0, c1, k600) client_id=b'local_test'
Sending SUBSCRIBE (d0) [(b'topic_1', 0)]
Subscribed return = (0, 1)
Received CONNACK (0, 0)
Connected Info
Received SUBACK

Subscribed None
Sending CONNECT (u1, p1, wr0, wq0, wf0, c1, k600) client_id=b'local_test'
Received CONNACK (0, 0)
Connected Info

编辑 1:

此外,我看到我的经纪人已将消息从发布者发送到客户端,但客户端无法接收到它。

1个回答

正如其他人在评论中提到/暗示的那样:
应该发生的实际顺序是:

首先正确设置您的回调(包括 on_message)。
呼叫连接。
等到您收到连接确认。
然后,发出订阅请求。(这实际上会通过 TCP 向代理发送一条消息。如果未完成连接,则不会发生这种情况。)
请注意,在订阅完成并且您获得肯定确认后,可能会有一小段时间订阅实际上并未在经纪人处完成。在使用计算机集群的大型代理中尤其如此。通常,这个不确定的时间很小。最多几百毫秒。
在订阅被确认后(一秒钟后,如果您可以延迟它),如果您从发布者发送消息,代理应该能够将其转发给您的客户,您应该能够看到它。