python - 重新连接后 Mqtt 不向订阅者发送数据
问题描述
我有一个 mqtt beoker,我正在尝试在 python 中连接和订阅。代码
client = mqtt.Client("P1",clean_session=True) #create new instance
client.on_connect = on_connect
client.on_message = on_message #attach function to callback
client.on_disconnect = on_disconnect
print("connecting to broker")
client.connect(broker_address, port=port) #connect to broker
print("Subscribing to topic","topic")
client.subscribe("topic")
client.loop_forever()
回调函数
def on_connect(client, userdata, flags, rc):
if rc==0:
print("connected OK Returned code=",rc)
print(client)
else:
print("Bad connection Returned code=",rc)
def on_disconnect(client, userdata, rc):
print("Client Got Disconnected")
if rc != 0:
print('Unexpected MQTT disconnection. Will auto-reconnect')
else:
print('rc value:' + str(rc))
try:
print("Trying to Reconnect")
client.connect(broker_address, port)
client.subscribe("topic")
print('tried to subscribe')
except:
print("Error in Retrying to Connect with Broker")
def on_message(client, userdata, message):
print("message received ")
所以问题是,客户端连接到代理,接收消息一段时间然后断开连接。一旦客户端断开连接,我就添加了重新连接。现在它已连接但客户端没有收到任何消息。输出
connecting to broker
Subscribing to topic unilever
connected OK Returned code= 0
<paho.mqtt.client.Client object at 0x7f454660dcf8>
message received
.
.
.
.
收到消息一段时间并断开连接。输出
Client Got Disconnected
Unexpected MQTT disconnection. Will auto-reconnect
Trying to Reconnect
tried to subscribe
connected OK Returned code= 0
<paho.mqtt.client.Client object at 0x7f454660dcf8>
有人可以帮我解释为什么会这样吗?
谢谢
解决方案
这是因为您在重新连接时默认获得一个新会话(因为您有clean_session=True
),因此您没有活动订阅。
将调用移动到回调client.subscribe('topic')
内部,on_connect
然后它将在重新连接时重新订阅。
推荐阅读
- mysql - 计数日期的子查询 - MYSQL
- php - Wordpress Docker Image,PHP 致命错误:内存不足
- sql - sqlite3 错误:“无法解析表”即使我已经重新制作了表
- reactjs - 在右键单击事件上反应传单
- html - 如何在网页中显示 dwg
- python - 我想在打开 .bat 文件后继续我的程序
- asp.net-ajax - 如何解决,当加载 ajax 日历页面然后在谷歌浏览器中显示错误类型的数字
- javascript - 三 js + GSAP - 渲染器颜色过渡
- safari - URL 中带有用户信息的 Safari 是否会忽略 target="_blank"
- javascript - tagify(js) 不会将标签保存到 wordpress