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

node mqtt why I get the published message three times

只是在玩弄 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 我可以看到 发表次数:三次 而不仅仅是

Published: Buffer 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

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

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

...有了这个:

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

...那么我猜您仍然会看到相同的日志输出。标记为 "Published:" 的日志记录可能来自 mqtt 本身的 node_module 而不是来自您的代码。通过更改您自己的日志记录,您可以确认这一点。

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

您正在记录客户端发送给服务器的所有消息,而不仅仅是 "publish" 消息。如果你只想要那些消息,你可以使用这个:

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