0

注意我EMQX用作代理和python-paho客户端库。我不确定是谁对这个问题负责。

如果发布者有一段时间没有发送任何消息,订阅者会断开连接,但也会再次重新连接(因为 loop_forever 会自动处理重新连接)。但是重连后,如果生产者再次开始发送数据,自动重连的服务器不会收到任何消息。在这种情况下,订阅者需要重新启动(手动重新连接)

我的订阅者

import paho.mqtt.client as mqttClient
import json
import datetime

def on_connect(client, userdata, flags, rc):

    if rc == 0:
        print("Connected to broker")

    else:
        print("Connection failed")

def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected MQTT disconnection. Will auto-reconnect")
    

def on_message(client, userdata, message):
    print(str(datetime.datetime.now())+str(message.payload) + "\n")


#broker_address= "3.121.233.176" 
broker_address= "address_of_the_broker" 
port = 1883                     
client = mqttClient.Client("clientLB1")               #create new instance
client.on_connect= on_connect                      #attach function to callback
client.on_message= on_message                      #attach function to callback
client.on_disconnect = on_disconnect
client.connect(broker_address,port,60)
client.subscribe("xdk1") #subscribe
client.loop_forever() #then keep listening forever
 

我的发布者:

import paho.mqtt.client as paho
import time
from random import random

def on_publish(client, userdata, mid):
    print("mid: "+str(mid))
 
client = paho.Client()
client.on_publish = on_publish
#client.connect("35.157.39.224", 1883)
client.connect("LBmqtt-1826452731.eu-central-1.elb.amazonaws.com", 1883)
client.loop_start()

while True:
    temperature = random()
    (rc, mid) = client.publish("xdk1", str(temperature), qos=1)
    time.sleep(.1)

如何解决这个问题呢?

4

1 回答 1

1

解决了

client = mqttClient.Client("client_name",clean_session=False) 

来自文档:

clean_session:确定客户端类型的布尔值。如果为 True,代理将在断开连接时删除有关此客户端的所有信息。如果为 False,则客户端是持久客户端,并且在客户端断开连接时将保留订阅信息和排队消息。

于 2021-05-20T16:10:27.290 回答