从python客户端订阅mqtt代理时未接收到所有数据

我有一个正在运行的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,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,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

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

riijlcvyp 回答:从python客户端订阅mqtt代理时未接收到所有数据

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3096860.html

大家都在问