Simple NodeJs App with MQTT

What is MQTT?

MQTT is a lightweight, publish-subscribe network protocol that transports messages between devices. The protocol usually runs over TCP/IP, however, any network protocol that provides ordered, lossless, bi-directional connections can support MQTT.

MQTT is used for data exchange between constrained devices and server applications. It keeps bandwidth requirements to an absolute minimum, handles unreliable networks, requires little implementation effort for developers, and is, therefore, ideal for machine-to-machine (M2M) communication.

Node JS Application using MQTT

Create a publish file. (pub.js)

const mqtt = require('mqtt');

const client = mqtt.connect('mqtt://broker.hivemq.com');

client.on('connect',function(){

    setInterval(()=>{
        const random = Math.random() * 50;
        console.log(random)

        if (random > 26){
            client.publish('ATM01','ATM 01 temperature is ' + random.toString());
        }

    },1000);
   

});

Create a Subscriber file. (sub.js)

const mqtt = require('mqtt');

const client = mqtt.connect('mqtt://broker.hivemq.com');

client.on('connect',()=>{

    client.subscribe('ATM01');
    console.log('Client has subscribed successfullly.');

});

client.on('message',(topic, message)=>{
    console.log("Alarming Message" + topic.toString() + ": " + message.toString());
})

Now, we need to execute the application. Open two command prompt, one for publisher (pub.js) and one for subscriber (sub.js)

In Publisher Command Prompt, execute "node pub.js"





In Subscriber Command Prompt, execute "node sub.js"






Both publisher and subscriber working.

Note: I am using mqtt://broker.hivemq.com as a MQTT broker.

Comments

Popular posts from this blog

Data Bound Controls in ASP.Net - Part 4 (FormView and DetailsView controls)

ASP.net: HttpHandlers

The Clickjacking attack and X-Frame-Options