0

我有一个 mosca mqtt 代理启动并运行。我从 python 客户端连接到代理,订阅特定主题以接收数据。我在接收数据时面临数据丢失的问题。我的代码

broker_address=""
port = ""

def on_message(client, userdata, message):
    time = datetime.now()
    print("message received at: "+str(time))


def on_connect(client, userdata, flags, rc):
    if rc==0:
        print("connected OK Returned code=",rc)
        time = datetime.now()
        print(time)
    else:
        print("Bad connection Returned code=",rc)

    print("Subscribing to topic","data/#")
    client.subscribe("data/#")


def on_disconnect(client, userdata, rc):
   print("Client Got Disconnected")
   print('rc value '+str(rc))
   time = datetime.now()
   print(time)
   if rc != 0:
       print('Unexpected MQTT disconnection. Will auto-reconnect')

   else:
       print('rc value:' + str(rc))


def mqttConnection():
    client = mqtt.Client(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
    client.loop_forever() #stop the loop


if __name__ == "__main__":
    mqttConnection()

和控制台输出

message received at: 2019-11-15 13:31:59.779071
message received at: 2019-11-15 13:31:59.788275
message received at: 2019-11-15 13:31:59.804362
Client Got Disconnected
rc value 1
2019-11-15 13:32:00.819480
Unexpected MQTT disconnection. Will auto-reconnect
connected OK Returned code= 0
2019-11-15 13:32:01.863997
Subscribing to topic data/#
message received at: 2019-11-15 13:32:02.678528
message received at: 2019-11-15 13:32:02.970585
message received at: 2019-11-15 13:32:03.858506
message received at: 2019-11-15 13:32:04.062929
message received at: 2019-11-15 13:32:04.210075
message received at: 2019-11-15 13:32:04.494648
message received at: 2019-11-15 13:32:04.838279
message received at: 2019-11-15 13:32:04.840228
message received at: 2019-11-15 13:32:06.209856
message received at: 2019-11-15 13:32:07.731949
message received at: 2019-11-15 13:32:07.985341
message received at: 2019-11-15 13:32:08.084985
message received at: 2019-11-15 13:32:08.783509
message received at: 2019-11-15 13:32:09.255180
Client Got Disconnected
rc value 1
2019-11-15 13:33:02.293644
Unexpected MQTT disconnection. Will auto-reconnect
connected OK Returned code= 0
2019-11-15 13:33:03.326783
Subscribing to topic data/#
message received at: 2019-11-15 13:33:04.214865
message received at: 2019-11-15 13:33:04.668272
message received at: 2019-11-15 13:33:04.774607
message received at: 2019-11-15 13:33:07.299220

第一次断线后,一秒内立即重新连接并开始接收消息。但第二次断线时,最后一条消息与disconnect回调打印的时间有1分钟的时间差。这一分钟差异中的数据将丢失。但是,如果我使用 MQTT Lens 检查数据,我连接到代理地址并订阅相同的主题,我也可以看到那一分钟的数据。因此,代理正在发送数据,但 python 客户端无法接收它。如果它在一分钟后断开连接,为什么它在一分钟内无法接收该数据。有人可以帮我弄这个吗?

4

0 回答 0