mqtt.js自动关闭连接

时间:2016-03-11 09:16:24

标签: node.js mqtt

我的mqtt.js客户端库有问题。 我正在尝试从emonhub接收消息。当我打电话

mosquitto_sub -v -u 'login' -P 'pass' -t 'emon/#'
一切都好。但是,当我尝试从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
(...)

这是我的代码:

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');
});

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您的消息处理程序中有client.end(),一收到客户端要退出的第一条消息

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