mosca icon indicating copy to clipboard operation
mosca copied to clipboard

client is undefined in server.on('published',function(packet,client){})

Open neilunadkat opened this issue 11 years ago • 3 comments

I just setup the MQTT server today. There were a couple of questions/doubts that I had.

  • Firstly in the on 'published' event I am getting the client as undefined. Is it a normal behaviour or am I doing something wrong? Here is my server code
var mosca = require('mosca');

var settings = {
  port: 1883,
  // persistence: mosca.persistence.Memory,
};

var server = new mosca.Server(settings);

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

server.on('ready', setup);

// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running');
}

and here is client

var mqtt    = require('mqtt');

var client  = mqtt.connect('mqtt://localhost:1883');

client.on('connect', function () {
  // client.subscribe('presence');
  console.log('Client Connected ');
  // client.publish('presence', 'Hello mqtt');
});

client.on('message', function (topic, message) {
  // message is Buffer
  console.log(message.toString());
  // client.end();
});

process.stdin.on('data', function (d) {
       client.publish('data','data');
  });

Do let me know if there is anything wrong here.

  • Sending message to a specific client (#214) I will be getting messages from the devices(clients) and I would like to send back an acknowledgment (after some basic processing). It would be nice to have a client.publish() API. Otherwise I can try and subscribe the client to the client id and then will have to maintain the client id to my own identifier for that particular device (client). (This was mentioned in the issue). The only issue I see for this is that I will have to start maintaining a map for this. Just trying to see if I can avoid that :).

This is some good work though :).

neilunadkat avatar May 15 '15 13:05 neilunadkat

I think you should implement authenticating process. See https://github.com/mcollina/mosca/wiki/Authentication-&-Authorization

uronly14me avatar May 18 '15 03:05 uronly14me

In the on('published') event the client might be undefined. There are some messages that are published by the broker itself, like stats. This is perfectly normal, albeit poorly documented.

This is a pub/sub system. Mosca has a publish method, to publish messages in the broker.

mcollina avatar May 18 '15 06:05 mcollina

Aah.. yes.. I realised that after filtering on topic. And it makes sense. Thanks .

neilunadkat avatar May 18 '15 09:05 neilunadkat