Search code examples
node.jsmosca

Mosca sends multiple messages continously


I have setup a node js server with Mosca running on it. Clients are able to connect to the Mosca server and publish a message. I need to the send an acknowledgment in the form of a message(subscribed to some topic) back to the client.

The below code sends multiple messages continuously once the message is published by the client. Am I missing anything?

 var settings = {
    port: 1882,
    backend: ascoltatore
 };

 var message = {
   topic: 'crofters',
   payload: 'OK', // or a Buffer
   qos: 2

 };

 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 ) {


    var packet_payload = packet.payload;
    packet_payload = packet_payload.toString();
    console.log('Published', packet_payload);

    server.publish(message, function() {
        console.log('done!');
    });


});

server.on('ready', setup);

function setup() {
   console.log('Mosca server is up and running');
}

Solution

  • The event listener server.on('published', function(packet, client){...} listens to every publishing events, including the server's.

    What is happening is that when you use server.publish(message, function(){...}) inside that listener it triggers another published event, which is immediately caught by the listener.

    It never stops publishing because it never stops catching its own events.