我在CloudMQTT
上运行,我的JS代码是这样的:
var mqtt_url = URL.parse('mqtt://m10.cloudmqtt.com:15272' || 'mqtt://localhost:1883');
var auth = (mqtt_url.auth || ':').split(':');
var url = "mqtt://" + mqtt_url.host;
var options = {
port: mqtt_url.port,
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: USERNAME,
password: PASSWORD,
};
// Create a client connection
var client = mqtt.connect(url, options);
client.on('connect', function() { // When connected
// subscribe to a topic
client.subscribe('relay', function() {
// when a message arrives, do something with it
client.on('message', function(topic, message, packet) {
// console.log(packet);
console.log("Received '" + message + "' on '" + topic + "'");
});
});
// subscribe to a topic
client.subscribe('photoresistor', function() {
// when a message arrives, do something with it
client.on('message', function(topic, message, packet) {
console.log("Received '" + message + "' on '" + topic + "'");
});
});
// publish a message to a topic
client.publish('relay', value, function() {
console.log("Message of ", value, " is published");
// client.end(); // Close the connection when published
});
});
我将 ESP8266
连接到光敏电阻,并且它每 5 秒将光敏电阻值发布到 photoresistor
主题。
好吧,每 5 秒我就会在我的 Node 服务器 (MeteorJS) 上收到四个相同的控制台日志。
I20170907-19:33:51.421(-4)? Received '156' on 'photoresistor'
I20170907-19:33:51.423(-4)? Received '156' on 'photoresistor'
I20170907-19:33:51.424(-4)? Received '156' on 'photoresistor'
I20170907-19:33:51.425(-4)? Received '156' on 'photoresistor'
I20170907-19:33:57.741(-4)? Received '39' on 'photoresistor'
I20170907-19:33:57.742(-4)? Received '39' on 'photoresistor'
I20170907-19:33:57.743(-4)? Received '39' on 'photoresistor'
I20170907-19:33:57.743(-4)? Received '39' on 'photoresistor'
I20170907-19:34:05.465(-4)? Received '37' on 'photoresistor'
I20170907-19:34:05.467(-4)? Received '37' on 'photoresistor'
I20170907-19:34:05.468(-4)? Received '37' on 'photoresistor'
I20170907-19:34:05.470(-4)? Received '37' on 'photoresistor'
I20170907-19:34:10.665(-4)? Received '161' on 'photoresistor'
I20170907-19:34:10.667(-4)? Received '161' on 'photoresistor'
I20170907-19:34:10.667(-4)? Received '161' on 'photoresistor'
I20170907-19:34:10.668(-4)? Received '161' on 'photoresistor'
知道什么可能导致 client.subscribe
函数或 CloudMQTT 输出多条相同消息吗?
最佳答案
似乎在某些情况下,在连接事件处理程序内订阅可能会导致重复订阅。 mqtt.js release 2.9.0 中解决了这种性质的问题。 ,如上所述here 。 因此,升级到最新的 mqtt.js 版本(当前为 2.13.1)可能会解决您的问题。
但是,另请注意 mqtt.js usage notes声明“从 v2.0.0 开始,如果 clean: true,订阅将在重新连接时恢复”。另请参阅here 。如果是这样,您似乎实际上根本不需要从连接事件处理程序中进行订阅,这有望从一开始就防止重复订阅的发生。
您应该可以在连接 Node.js 客户端时重新启动 CloudMQTT 代理来测试上述假设。这是否会导致您开始看到重复的消息?如果是这样,我相信补救措施确实是将您的订阅移到连接事件处理程序之外。
关于javascript - MQTT.js 订阅从代理接收多条相同消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46106558/