Lisa
Lisa

Reputation: 675

connect to mqtt broker after disconnecting from another broker using nodejs lib

The scenario that i want to implement is , first my service will connect to a mqtt broker , when i receive a message from a will topic , i want to disconnect it from the broker my mqtt client was connected and connect to some other broker.is it possible to do this using nodejs library??

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://192.168.100.3')

client.on('connect', function () {
  console.log("connected to broker")
  client.subscribe('mqtt_node_subscribe')
  client.publish('mqtt_node_publish', 'Hello mqtt')
})
client.on('close',function(){
  console.log("connection closed")
})
client.on('message', function (topic, message) {
  // message is Buffer 
  console.log("message arrived")
  
    client.end()
    client = mqtt.connect('mqtt://192.168.100.14')
  }})

I was able to disconnect from the current broker , but unable to connect to the other one, after disconnection Console messages are:

connected to broker
message arrived
connection closed

Upvotes: 1

Views: 3381

Answers (1)

hardillb
hardillb

Reputation: 59628

You are replacing the client object so you need to recreate all the event handlers

e.g.

client.on('message', function (topic, message) {
  // message is Buffer 
  console.log("message arrived")

  client.end()

  client = mqtt.connect('mqtt://192.168.100.14');
  client.on('connect', function () {
  ...
   });
   client.on('close',function(){
   ...
   })
}})

Upvotes: 1

Related Questions