Search code examples
javascriptnode.jsmqttmosquittobroker

MQTT.js: How to close / connect to another broker after failed connection attempt? (for using bridged mosquitto)


I did set up two mosquitto broker with websocket support and am able to connect to them with mqtt.js

Now I tried to implement a fault-prove version with an array of possible mqtt brokers, which should be tried to connect to in order until a successful connection. If a connection fails, the next broker should be tried... so far so good, but if i try to connect to an offline broker, somehow mqtt.js tries to reconnect endlessly. I am not able to close the connection attempt and connect to the next one.

var client = mqtt.connect("ws://firstbrokerip:9001");

client.on('connect', function() {
	//consoleLog("[BROWSER] MQTT js-Client:"," Connected","green");
	client.subscribe("testchannel");	
});

client.on('offline', function() {
	//consoleLog("[BROWSER] MQTT js-Client:", ' Offline',"red");
  client.end();
	client = mqtt.connect("ws://secondbrokerip:9001");
});

Any ideas of how can I close the connection and connect to the next ? (Plz don't care about the custom ConsoleLog function)


Solution

  • You don't need to implement fail over, it's baked into the module:

    From the mqtt.js doc (https://github.com/mqttjs/MQTT.js#connect)

    You can also specify a servers options with content: [{ host: 'localhost', port: 1883 }, ... ], in that case that array is iterated at every connect.

    So you pass the connect method options object with a key called servers which is an array of brokers to connect to.

    client = mqtt.connect({
      servers: [
        {
          host: 'firstbroker.ip',
          port: 9001,
          protocol: 'ws'
        },
        {
          host: 'secondbroker.ip',
          port: 9001,
          protocol: 'ws'
        }
      ]
    });