I have the below code to publish to a MQTT broker every 3 seconds, but it is not working:
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://test.mosquitto.org');
var topic = 'test-topic';
client.on('connect', function () {
client.subscribe(topic);
setInterval(function() {
client.publish(topic, Date.now().toString());
console.log('hello');
}, 3000);
});
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString());
client.end();
});
I can see the hello message being printed out every 3 seconds, but not my mqtt published date messages.
If I remove the setInterval function and use client.publish(...) instead, it only publishes once and exit.
Update
after removing the client.end(), it is working as expected.
In
client.on('message')you need to removeclient.end()because mqtt is finished when it receives the first message.