Python/paho MQTT - 未收到消息

Python/paho MQTT - not receiving messages

我是使用 MQTT 的新手,我想同时 运行 两个 Python 程序:一个用于向主题发布消息,另一个用于在消息发布到时打印消息话题。但是,打印消息的回调函数对我不起作用。

这是我的两个程序:

发布消息:

import paho.mqtt.client as mqtt

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

client = mqtt.Client(client_id="clientID")
client.on_connect = on_connect
client.username_pw_set(username="username", password="password")
client.loop_start()
client.connect("node02.myqtthub.com", 1883)

while True:
    client.publish("my/topic", "test")

订阅并打印消息:

import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
    print(msg.payload.decode())

def on_connect(client, userdata, flags, rc):
    print("Connected! Result code: " + str(rc))
    client.subscribe("my/topic")

client = mqtt.Client(client_id="clientID")
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username="username", password="password")
client.connect("node02.myqtthub.com", 1883)
client.loop_forever()

有人可以帮我解决这个问题吗?

两个程序都在使用 client_id="clientID"mqtt spec

If the ClientId represents a Client already connected to the Server then the Server MUST disconnect the existing Client [MQTT-3.1.4-2].

因此,无论哪个应用连接到第二个,都会导致第一个断开连接。要解决此问题,请更改其中一个应用程序中的客户端 ID。

注意:这是对明显错误的评论。提问时请说明您看到的情况(任何输出、错误、您尝试过的内容等),因为可能还有其他问题。