使用 Paho Python:为什么没有触发回调“on_message”?

Using Paho Python: Why the callback “on_message” is not triggered?

我不明白为什么在我订阅的同一主题中正确发布消息时没有触发回调“on_message”。 这是我使用的代码:

def on_connect(client, userdata, flags, rc):
    """ Callback called when connection/reconnection is detected """
    print("Connect %s result is: %s" % (host, rc))

    # With Paho, always subscribe at on_connect (if you want to
    # subscribe) to ensure you resubscribe if connection is
    # lost.
    client.subscribe("some/message/to/publish")

    if rc == 0:
        client.connected_flag = True
        print("connected OK")
        return

    print("Failed to connect to %s, error was, rc=%s" % rc)
    # handle error here
    sys.exit(-1)


def on_message(client, userdata, msg):
    """ Callback called for every PUBLISH received """
    print("%s => %s" % (msg.topi, str(msg.payload)))


# Define clientId, host, user and password
client = mqtt.Client(client_id=client_id, clean_session=clean_session)
client.username_pw_set(user_name, password)
client.subscribe("some/message/to/publish")
client.on_connect = on_connect
client.on_message = on_message

# connect using standard unsecure MQTT with keepalive to 60
client.connect(host, port, keepalive=60)
client.connected_flag = False
while not client.connected_flag:  # wait in loop
    client.loop()
    time.sleep(1)

client.subscribe("some/message/to/publish")
# publish message (optionally configuring qos=1, qos=2 and retain=True/False)
ret = client.publish("some/message/to/publish", "{'status' : 'on'}")
client.loop()

print("Publish operation finished with ret=%s" % ret)

client.disconnect()

这是我得到的退出代码:

Connect node02.myqtthub.com result is: 0
connected OK
Publish operation finished with ret=(0, 3)

Process finished with exit code 0

调用 client.loop() 仅处理客户端网络事件处理器的一次迭代。

client.publish() 的调用可能需要多个事件才能完成(取决于消息的大小和所使用的 QOS),并且在代理将消息发送回客户。 client.subscribe() 的调用也会消耗至少一次事件循环调用。 所以单次调用 client.loop() 是不够的。

除非您非常清楚自己在做什么,否则您可能应该使用 client.start_loop()/client.stop_loop() 函数来 运行 单独线程上的事件处理循环。