0

I am having the following code in node.js. It connects fine to the broker I have set on my personal website/server, and it is able to send and listen to the events from the server.js.

My problem is that it does not listen to other events that are sent to the broker from other devices. How can I make sure that the code below will manage to listen to all events from the broker?

Thanks

var mqtt = require('mqtt')
var MQTT_TOPIC = "homeGet/light";
var MQTT_ADDR = "mqtt://broker.example.org:80";
var MQTT_PORT = 80;
var client  = mqtt.connect(MQTT_ADDR,{clientId: "webClient", keeplive: 1, clean: false, debug:true});

var express = require('express');
var socket = require('socket.io');

//store the express functions to var app
var app = express();

//Create a server on localhost:5000
var server = app.listen(process.env.PORT || 5000);

//var server = app.listen((process.env.PORT || 3000, function(){
  //console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
//});
//host content as static on public
app.use(express.static('public'));

console.log("Node is running on port 5000...");

//MQTT
client.on('connect', function () {
    client.subscribe(MQTT_TOPIC, { qos: 2 });
    client.publish(MQTT_TOPIC, '1000');
});
client.on('message', function (topic, message) {
    // message is Buffer
    console.log(message.toString());
    client.end();
});
client.on('error', function(){
    console.log("ERROR")
    client.end()
})
client.on('offline', function() {
    console.log("offline");
});
client.on('reconnect', function() {
    console.log("reconnect");
});
S.D.
  • 11
  • 1
  • 5

1 Answers1

0

You have client.end() in your client.on('message',function(message){...}) callback.

This will disconnect the client as soon as it receives it's first message.

Assuming you copied this from the example in the README.md for the mqtt package on npm. That example is specifically set up to receive only one message.

hardillb
  • 54,545
  • 11
  • 67
  • 105