首页 > 解决方案 > 重新连接后 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>

有人可以帮我解释为什么会这样吗?

谢谢

标签: pythonmqttpublish-subscribepahomessagebroker

解决方案


这是因为您在重新连接时默认获得一个新会话(因为您有clean_session=True),因此您没有活动订阅。

将调用移动到回调client.subscribe('topic')内部,on_connect然后它将在重新连接时重新订阅。


推荐阅读