US Toll-Free - +1 866 941 5117


Real Time Communication With MQTT – It’s in Trend (Part – 2)


My previous blog was all about server (broker) creation and options, provided during creation. In this blog post, I am going to discuss available events of Mosca and the step by step procedure of creating MQTT client.

Let’s start with Mosca events first. Mosca emits these events for the server.

  1. clientConnected :  when a client is connected the client is passed as a parameter.
    ex:  server.on( ‘ clientConnected ‘ , callback);
  2. clientDisconnecting :  when a client is being disconnected the client is passed as a parameter.
    ex:  server.on( ‘ clientDisconnecting ‘, callback);
  3. clientDisconnected :   when a client is disconnected the client is passed as a parameter.
                                    ex:  server.on( ‘ clientDisconnected ‘, callback);
  4. published :   when a new message has published the packet and the client are passed as parameters.
    ex:  server.on(‘published’, callback).
    Here you will receive ‘ packet ’ and ‘ client’ as arguments of the callback function. The client will contain the client object from where the message is published from and the packet object contains the details of the message/packet that is sent by the client.

    Sample packet object: { topic: 'topic/child',
      payload: <Buffer 7b 22 6e 61 6d 65 22 3a 22 73 61 69 6b 61 74 22 2c 22 74 69 74 6c 65 22
                3a 22 68 61 6a 72 61 22 7d>,
      messageId: '4JftrH60W-',
      qos: 0,
      retain: false }
    • topic :   topic name where the message is published.
    • payload :   The payload property contains the message as a buffer of bytes. To get the readable string format convert it to UTF-8. i.e.
    • messageId :   it’s a random unique Id .
    • QoS :   QoS is 0 by default ,you can set it to 1 for the guarantee of service.
    • retain :   retain is also by default false. But if you set it to true, this message will be treated a bit differently.In that case, the message will be stored and will be published by the broker whenever a new client will subscribe to the same topic the retain message has (It’s like a welcome  message ) . But please remember only the latest retain message will be stored per topic.

  5. subscribed :   when a client is subscribed to a topic the topic and the client are passed as parameters.
    ex: server.on( ‘ subscribed ‘, callback);
  6. unsubscribed :  when a client is unsubscribed to a topic,the topic and the client are passed as parameters.
    ex: server.on( ‘ unsubscribed ‘, callback);
  7. ready :   when the server is ready.
    ex: server.on( ‘ ready ‘, callback);
  8. error :   when the server has thrown an error.
    ex: server.on( ‘ error ‘, callback);

As we have created our server already, now we need to create a client to test whether we have successfully implemented the MQTT client – server application.

Step 1 : install MQTT using npm

npm install mqtt@* --save

Step 2: create a client_one.js file and load the MQTT module.

var mqtt = require('mqtt');

Step 3: now connect your client with MQTT server.

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

The connect function takes two arguments host URL and options. Protocol can be mqtt://, ws:// mqtts:// and wss:// (ws stand for WebSocket). For secure connection provide details in the options argument.

var options = {
  port: PORT,
  keyPath: KEY,
  certPath: CERT,
  rejectUnauthorized : false
}//use this for secure connection and pass as argument to mqtt.connect

Step 4 :  now subscribe to a topic.

client.subscribe('topic/child',{qos:1}); //qos is set to 1 to receive the persistent messages without external storage (not in offline mode,for offline mode you need to set persistence).default is 0.

Step 5:  after subscription now let’s publish a message.

client.publish('topic/child', JSON.stringify({ name: "saikat", title: "hajra" })); // I am sending a json value. You can send any value as text

Step 6: now create an another client in client_two.js file with above-mentioned procedure. Now we are going to listen on ‘topic/child’ channel. MQTT emits message event whenever there is message available in a channel.

client.on('message', function(topic, message) { 
         }   //message is again a bytes of buffer. Topic is the name of the topic where the message is published

Step 7:  run server.js , client_one.js , client_two.js in separate tabs using node Js.

Step 8: To unsubscribe from a topic.

client.unsubscribe('topic/child',callback); // just need to pass the topic name

To use mqtt.js from browser just download mqtt.js and implement it in this way.

<script src="/mqtt.js"></script>
var client = mqtt.connect({hostaddress here});
client.subscribe("mqtt/demo", { qos: 1 , retain : true }); // qos and retain part optional as described earlier

      client.on("message", function(topic, payload) {
        alert([topic, payload].join(": "));

Hurray !!!!!  we have successfully implemented the MQTT  client application .For more details and example, visit my GitHub Page.

Saikat Hajra

Saikat likes to play around with Codes. And Javascript is one of the playground for him. Beside coding he likes to introduce himself with cutting-edge technologies like image processing , machine learning. And travelling is the only craze which often keeps him away from Coding.