我在node.js中有以下代码。它连接到我在我的个人网站/服务器上设置的经纪人,并且能够发送和收听服务器的事件。
。我的问题是,它不听其他设备发送给经纪人的其他事件。我如何确保下面的代码将设法收听经纪人的所有事件?
谢谢
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");
});
您的 client.end()
中有CC_1回调。
这将在收到第一个消息后立即断开连接。
假设您从readme.md中的示例中复制了此示例,则在NPM上的MQTT软件包中复制了此内容。该示例专门设置为仅接收一条消息。