top of page

Using MQTT.JS library

MQTT (Message Queuing Telemetry Transport) is a lightweight publish-subscribe messaging protocol designed for use in IoT (Internet of Things) and M2M (Machine to Machine) communication.

MQTT protocol is a client-server protocol, where the clients are the IoT devices, and the server is the broker that facilitates communication between the devices.

Following is an example of how to create an MQTT client using the MQTT.js library in JavaScript:

const mqtt = require('mqtt')

// Connect to the MQTT broker
const client = mqtt.connect('mqtt://')

// Subscribe to a topic

// Publish a message to a topic
client.publish('my/topic', 'Hello Agilytics!')

// Handle incoming messages
client.on('message', (topic, message) => {
  console.log(`Received message on topic ${topic}: ${message}`)

// Handle errors
client.on('error', (error) => {
  console.error(`Error: ${error}`)

// Disconnect from the MQTT broker

This code uses the mqtt library to connect to an MQTT broker, subscribe to a topic, publish a message to that topic, and handle incoming messages and errors. You'll need to replace mqtt:// with the address of your own MQTT broker.

37 views0 comments


bottom of page