Monday , July 4 2022
Home / Internet of Things / MOSCA MQTT Server Using Node JS

MOSCA MQTT Server Using Node JS

Before we going to start something. We should know about what is the MQTT server and how it works. MQTT (Message Queuing Telemetry Transport) Protocol. This protocol allows the machine to communicate with each other regardless of the power consumption for the lightweight and small sensor and actuators. Moreover, in this Protocol, we have lots of QoS. Means that according to the environment you set the QoS.

There are three basic levels of QoS 0,1,2.

There are too many things which are related to this but for now, you just check out the actual document here

Now, let’s talk about the MQTT main components without these it will not be working as declared. The things are:

  1. Broker
  2. Publisher
  3. Subscriber

The Broker act like we saw in over daily routine life Broker. It means that every party should now the Broker. But, no seller or buyer will know it.

Here the Broker code which was running in Node.JS

var mosca = require('mosca');
var settings = {

var server = new mosca.Server(settings);

server.on('ready', function(){

After this Publisher comes in the live stream. As the Word describes its nature Publisher behave like the seller in this scope.

Here the Publisher code which was running in Node.JS

var mqtt = require('mqtt');
var client  = mqtt.connect('mqtt://<mqtt-server-ip>');
client.on('connect', function () {
setInterval(function() {
client.publish('onoff', 'Turn on the light');
console.log('Message Sent');
}, 5000);

Finally, the thing which ends the story is the Subscriber. I think now you know the work of this thing. It actually works like the buyer.

Here the Subscriber code which was running in Node.JS

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://<mqtt server ip>')
client.on('connect', function () {
client.on('message', function (topic, message) {
context = message.toString();


About Faheem

An adaptable and responsible Software Engineer, who enjoys working with computers and the opportunity to learn new skills and work with new technologies is particularly attractive to me.

Check Also

How can IoT Helps in Our Education?

Introduction Today, the objects are very smarter and very portable in all respects due to …

Leave a Reply

Your email address will not be published.