node mqtt为什么我三次获得已发布的消息

时间:2015-06-21 15:07:09

标签: node.js 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

2 个答案:

答案 0 :(得分:2)

您正在记录客户端发送服务器的所有消息,而不仅仅是&#34;发布&#34;消息。如果您只想要这些消息,可以使用:

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

答案 1 :(得分:1)

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

div#my_poststypewidget-18 > .specials li {
  background-color: gold;
}

......用这个:

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

...然后我猜你还会看到相同的日志输出。记录标记的可能性是&#34;已发布:&#34;来自mqtt本身的node_module,而不是来自你的代码。通过更改自己的日志记录,您可以确认这一点。

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