我正在使用 MQTT Paho 项目中的以下代码来订阅来 self 的 mqtt 代理的消息。我使用 mosquitto_sub 测试了连接,并在那里收到了消息。但是,当我运行以下代码时,它没有收到任何消息,也没有打印任何输出。我检查了主题和主持人。
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, 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("test")
# The callback for when a PUBLISH message is received from the server.
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("localhost", 1883, 60)
client.loop_forever()
代理记录以下错误:
Invalid protocol "MQTT" in CONNECT from ::1.
Socket read error on client (null), disconnecting.
编辑感谢@hardillb指出过时的MQTT版本。
在我执行以下操作后一切正常:
- sudo apt-get purge mosquitto
- sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
- sudo apt-get update
- sudo apt-get install mosquitto
这很可能是因为您使用的是旧版本的 mosquitto,而 python 需要支持 MQTT 3.1.1 的新版本
尝试更改代码,如下所示:
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, 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("test")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
# Change made HERE
client = mqtt.Client(protocol=MQTTv31)
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost", 1883, 60)
client.loop_forever()
您还应该尽快升级您的经纪商,该版本已经过时,并且存在许多已知问题,当前版本是 1.4.10
我是一名优秀的程序员,十分优秀!