MQTT 客户端收不到消息

MQTT Client not receiving messages

我正在使用 MQTT Paho 项目中的以下代码订阅来自我的 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 版本。

我执行以下操作后一切正常:

  1. sudo apt-get purge mosquitto
  2. sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
  3. sudo apt-get 更新
  4. 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