Skip to content

erkanina/mqtt-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

mqtt-demo on localhost

Requirements

  1. In command line go to the installation directory of mosquitto and run mosquitto in verbose mode so that you can see console messages.By default the broker will start listening on port 1883.
  mosquitto -v
  1. Go to the project directory and clone the repository
  git clone https:/erkanina/mqtt-demo.git
  1. Install mqtt package
  npm install mqtt
  1. You will need two console windows, one for publisher and one for subscriber. Run both scripts as below;
  Node publisher.js

  Node subscriber.js

Screenshot

publisher

const mqtt = require("mqtt");
const client = mqtt.connect('mqtt://localhost');

var counter = 0;

function publishData() {
    client.publish(
        "mqtt/myCounter",
        JSON.stringify(`Timer:${counter}`)
      );

      console.log("Published : " + counter);

      counter++;
}

setInterval(publishData, 3000);

subscriber

const mqtt = require('mqtt')
const client = mqtt.connect('mqtt://localhost')

client.on('connect', () => {
  console.log('Connected to broker');

  client.subscribe('mqtt/myCounter');
  console.log('Subscribed to \"mqtt/myCounter\"');
});

client.on('message', (topic, payload) => {
    switch(topic){
        case 'mqtt/myCounter':
            console.log('Rx message : ' + payload.toString());
        break;
    }
});

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published