简体   繁体   中英

Node JS mqtt client doesn't received subscribed messages when broker goes down and comes up

I have created a mqtt node js client. My connection options are as follows.

mqttOptions = {
clientId: '100',
keepAlive: 1000,
clean: false,
reconnectPeriod: '1000',
will: willMessage
};

I disconnected the server and brought it up again, while the client was still running. The client had the logic to publish every 1 second. Though the client was publishing after this reconnect, it was not receiving the message. It was subscribed to its own message topic. Since I set the clean option to be false, should it not subscribe to the topics on the reconnect and start receiving them?

在此处输入图片说明

Below is how I'm establishing the connection.

this.client = mqtt.connect(url, mqttOptions);

and below is how I'm subscribing.

this.client.subscribe(topic);

What am I doing wrong here? Please advice.

clean: 'false',

Should 'false' definitely be a string? I presume it should be a boolean.

We faced this issue with EMQ as the broker and with mqtt library for NodeJS. When it was mosquitto as broker, the client reconnects and gets all the messages it had subscribed. But, if it subscribes again, it gets n number of copies of the same message. As per the library document, it is recommended to check for connack and connack.sessionPresent for previous subscriptions.

We subscribed to all events of client and found that offline is the one that is called when the broker goes down. Then the reconnect and close gets called until the broker is up. Hence, here is how we did it. On offline , end the client forcefully and on completion of end, create a new client - the same function that was used to create client:

doConnect() {
    this.client = mqtt.connect('mqtt://myhost', this.myOptionsIfAny);
    this.client.on('connect', () => {
        this.client.subscribe('mytopics');
        this.client.on('message', (topic, message) => {
            // do processing
        });
        this.client.on('offline', () => {
            this.client.end(true, () => {
                doConnect();
            });
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM