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.
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 }
packet.payload.toString("utf-8").
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> <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(": ")); }); </script>
Hurray !!!!! we have successfully implemented the MQTT client application .For more details and example, visit my GitHub Page.