pmlody
pmlody

Reputation: 23

mqtt.js auto close connection

I have problem with mqtt.js client library. I am trying to receive messages from emonhub. When I call

mosquitto_sub -v -u 'login' -P 'pass' -t 'emon/#'

everything is OK. But when I try do that from nodejs:

[2016-03-11 10:01:03.771] [INFO] [default] - mqtt connected
[2016-03-11 10:01:07.979] [INFO] [default] - emon/emonpi/power1 0
[2016-03-11 10:01:07.994] [INFO] [default] - mqtt closed
[2016-03-11 10:01:08.002] [INFO] [default] - emon/emonpi/power2 0
(...)

This is my code:

var mqtt = require('mqtt');

var client  = mqtt.connect('mqtt://127.0.0.1:1883', {
    username: 'login',
    password: 'pass'
});

client.on('connect', function () {
    console.log('mqtt connected');

client.subscribe('emon/emonpi/#');

client.on('message', function (topic, message) {
        // message is Buffer
        console.log(topic + ' ' + message.toString());
        client.end();
    });
});

client.on('error', function(error) {
    console.log('mqtt error: ' + error);
});

client.on('close', function() {
    console.log('mqtt closed');
});

client.on('offline', function() {
    console.log('offline');
});

client.on('reconnect', function() {
    console.log('reconnect');
});

Any ideas?

Upvotes: 1

Views: 7756

Answers (1)

hardillb
hardillb

Reputation: 59608

You've got client.end() in your message handler, as soon as you receive your first message the client is going to exit

client.on('message', function (topic, message) {
        // message is Buffer
        console.log(topic + ' ' + message.toString());
        client.end();  <---- HERE
    });
});

Upvotes: 3

Related Questions