在使用 node.js 的 mqtt.js 时,我发现 client.connected 的值似乎是错误的,或者我误解了某些内容。
我做了这个教程http://thejackalofjavascript.com/getting-started-mqtt/一切正常。
我试图更多地了解 mqtt,所以我查找了 https://www.npmjs.com/package/mqtt#mqttclientconnected 、client.connected的说明:
Boolean : set to true if the client is connected. false otherwise.
为了看看它是否有效,我修改了第一行的源代码,如下所示
var mqtt = require('mqtt')
client = mqtt.connect('mqtt://localhost');
if (client.connected == true) {
console.log("Connection successful.")
}
else{
console.log("Something went wrong.")
}
client.subscribe('presence');
console.log('Client publishing.. ');
client.publish('presence', 'Client 1 is alive.. Test Ping! ' + Date());
client.end();
我刚刚添加了 if 子句。执行脚本时,我总是收到消息,出现问题,ergo:已连接 --> false。
但为什么呢?
最佳答案
问题是 mqtt.connect()
调用是异步的。所以它在实际连接之前就返回了。这意味着当您在调用 mqtt.connect()
后立即测试 mqtt.connected
时,它仍然会是 false,因为它实际上尚未完成连接。
您需要注册事件处理程序,以便在客户端实际连接时得到通知。
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://localhost');
client.on('connected',function(){
client.subscribe('presence');
console.log('Client publishing.. ');
client.publish('presence', 'Client 1 is alive.. Test Ping! ' + Date());
});
client.on('message',function(topic,message){
console.log("received message on " + topic);
console.log(message.toString());
client.end();
});
此代码连接到代理,订阅主题presence
,然后向同一主题发布消息。当它收到有关 presence
主题的消息时,它会将其打印出来然后退出。
关于javascript - mqtt.js |尽管客户端似乎已连接,但 client.connected 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40589613/