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

cvg*_*cvg 5 python publish-subscribe messagebroker mqtt paho

我有一个 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
Run Code Online (Sandbox Code Playgroud)
print("connecting to broker")
client.connect(broker_address, port=port) #connect to broker
print("Subscribing to topic","topic")
client.subscribe("topic")
client.loop_forever() 
Run Code Online (Sandbox Code Playgroud)

回调函数

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 ")

Run Code Online (Sandbox Code Playgroud)

所以问题是,客户端连接到代理,接收消息一段时间然后断开连接。我已经添加了客户端断开连接后的重新连接。现在已连接,但客户端未收到任何消息。输出

connecting to broker
Subscribing to topic unilever
connected OK Returned code= 0
<paho.mqtt.client.Client object at 0x7f454660dcf8>
message received
.
.
.
.

Run Code Online (Sandbox Code Playgroud)

收到消息一段时间后就断线了。输出

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>
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解释为什么会发生这种情况吗?

谢谢

har*_*llb 7

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

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