DEV Community

Cover image for Using MQTT.JS library
Paritosh Gupta
Paritosh Gupta

Posted on

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://broker.agilytics.in')

// Subscribe to a topic
client.subscribe('my/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
client.end()
Enter fullscreen mode Exit fullscreen mode

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://broker.agilytics.in with the address of your own MQTT broker.

Top comments (0)