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: willMessa
Solution 1:
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();
});
});
}
Post a Comment for "Node Js Mqtt Client Doesn't Received Subscribed Messages When Broker Goes Down And Comes Up"