gpt4 book ai didi

python - MQTT客户端收不到消息

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:43 25 4
gpt4 key购买 nike

我正在使用 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版本。

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

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

关于python - MQTT客户端收不到消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40061342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com