重连后Mqtt不向订阅者发送数据

Mqtt doesn't send data to subscriber after reconnection

我有一个 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 回调内部,然后它会在重新连接时重新订阅。