Python MQTT客户端未接收消息

Python MQTT客户端未接收消息,python,publish-subscribe,mqtt,Python,Publish Subscribe,Mqtt,我正在使用MQTT Paho项目中的以下代码从我的MQTT代理订阅消息。我使用mosquitto\u sub测试了连接,并在那里收到了消息。但是,当我运行下面的代码时,它不会收到任何消息,也不会打印输出。我检查了主题和主持人 import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, u

我正在使用MQTT Paho项目中的以下代码从我的MQTT代理订阅消息。我使用
mosquitto\u 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添加存储库ppa:mosquitto dev/mosquitto ppa
  • sudoapt获得更新
  • 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

    当你说不起作用时,你有任何输出吗?还有,您在哪个平台上运行此操作?完全没有输出。如果您甚至没有收到“已连接结果代码…”消息,那么您应该检查代理日志,看看它是否显示了客户端未连接的原因。您发布的代码在这里运行良好我添加了由brokerWhat broker记录的错误消息,您使用的是什么版本?