node mqtt why I get the published message three times

1k Views Asked by At

Just playing around with mqtt and mosca node module

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();

If I run client.js in the server console I can see Published: three times and not just

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
2

There are 2 best solutions below

0
On BEST ANSWER

You're logging all messages that the client sends the server, not just the "publish" messages. If you only want those messages, you can use this:

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

If you change this line in your server.js:

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

...with this:

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

...then I'm guessing you'll still see the same log output. It's possible that the logging tagged "Published:" is coming from the node_module for mqtt itself and not from your code. By changing your own logging you could confirm this.

Also... I think you often see two clients with this protocol. One subscribes and one publishes. Here's a good tutorial, btw. http://thejackalofjavascript.com/getting-started-mqtt/