MQTT.js订阅接收来自代理的相同消息的倍数

我在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秒钟就会在节点服务器(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版本2.9.0中讨论了这种性质的问题。 因此,升级到最新的mqtt.js版本(目前是2.13.1)可能会解决您的问题。

但是请注意, mqtt.js使用说明指出 :“从v2.0.0开始,如果clean:true,则在重新连接时恢复订阅”。 另见这里 。 如果是这样的话,看起来你根本不需要在你的连接事件处理程序中进行订阅,这应该有利于防止重复订阅的发生。

您应该可以testing上述假设,只需在连接node.js客户端时重新启动CloudMQTT代理即可。 这是否会导致您看到重复的消息? 如果是这样,我相信补救措施的确是简单地将您的订阅移到连接事件处理程序之外。