节点mqtt为什么我得到发布的消息三次

只是玩弄mqtt和mosca节点模块

server.js

var mosca = require('mosca') var settings = { port: 1884 }; //here we start mosca var server = new mosca.Server(settings); server.on('ready', setup); // fired when the mqtt server is ready function setup() { console.log('Mosca server is up and running') } // fired whena client is connected server.on('clientConnected', function(client) { console.log('client connected', client.id); }); // fired when a message is received server.on('published', function(packet, client) { console.log('Published: ', packet.payload); }); // fired when a client subscribes to a topic server.on('subscribed', function(topic, client) { console.log('subscribed : ', topic); }); // fired when a client subscribes to a topic server.on('unsubscribed', function(topic, client) { console.log('unsubscribed : ', topic); }); // fired when a client is disconnecting server.on('clientDisconnecting', function(client) { console.log('clientDisconnecting : ', client.id); }); // fired when a client is disconnected server.on('clientDisconnected', function(client) { console.log('clientDisconnected : ', client.id); }); 

client.js

 var mqtt = require('mqtt') var client = mqtt.connect({ host: 'localhost', port: 1884 }); client.subscribe('presence'); console.log('Client publishing.. '); client.publish('presence', 'Client 1 is alive.. Test Ping! ' + Date()); client.end(); 

如果我在服务器控制台中运行client.js,我可以看到发布:三次,而不仅仅是

发布:缓冲区43 ……

 Mosca server is up and running client connected mqttjs_bc22cc7a Published: mqttjs_bc22cc7a subscribed : presence Published: mqttjs_bc22cc7a Published: <Buffer 43 6c 69 65 6e 74 20 31 20 69 73 20 61 6c 69 76 65 2e 2e 20 54 65 73 74 20 50 69 6e 67 21 20 53 75 6e 20 4a 75 6e 20 32 31 20 32 30 31 35 20 31 36 3a ... > unsubscribed : presence clientDisconnected : mqttjs_bc22cc7a 

您将logging客户端发送服务器的所有消息,而不仅仅是“发布”消息。 如果你只想要这些消息,你可以使用这个:

 server.on('published', function(packet, client) { if (packet.cmd === 'publish') { console.log('Published: ', packet.payload); } }); 

如果您在server.js中更改此行:

  console.log('Published: ', packet.payload); 

…有了这个:

  console.log('My Published: ', packet.payload); 

…然后我猜你仍然会看到相同的日志输出。 标记为“Published:”的logging可能来自node_module,而不是来自您的代码。 通过改变你自己的日志logging你可以确认这一点

另外…我想你经常看到有这个协议的两个客户。 一个订阅和一个发布。 这是一个很好的教程,顺便说一句。 http://thejackalofjavascript.com/getting-started-mqtt/