AnOldSoul
AnOldSoul

Reputation: 4197

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?

enter image description here

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.

Upvotes: 3

Views: 3367

Answers (2)

James Jithin
James Jithin

Reputation: 10565

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();
            });
    });
}

Upvotes: 3

ralight
ralight

Reputation: 11608

clean: 'false',

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

Upvotes: 1

Related Questions