Python paho-mqtt连接到MQTT代理

时间:2018-09-11 17:38:03

标签: python mqtt mosquitto messagebroker

我正在使用此python脚本实现Paho(MQTT)订户,但我无法获得任何响应消息。我能够通过使用mosquitto_sub -t "" -d -h -p 8883 --psk foo --psk-identity bar --insecure --tls-version tlsv1来预订mqtt brokerin命令提示符

import paho.mqtt.client as mqtt

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

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("*********")

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("*********", 8883, 60)

client.loop_forever()

当我在python脚本上运行时,它不响应任何错误或消息,而是继续循环运行,我也逐行运行它,而当我运行client.connect("*********", 8883, 60)时,它仅显示 0 。请注意,此处没有psk和psk身份,我们无法连接到代理。

谢谢

1 个答案:

答案 0 :(得分:0)

请仔细检查您的主题,有时缺少/或#会导致此问题。

尝试一下

def on_message(client, userdata, msg):
   print("Message Recieved from broker: " + msg.payload.decode())