Connect FlowMQ with MQTT.js
FlowMQ's native support for MQTT makes it an excellent choice for JavaScript and Node.js applications. This guide will walk you through using MQTT.js
, a popular and versatile MQTT client, to connect to FlowMQ, publish messages, and subscribe to topics.
Prerequisites
Before you start, ensure you have the following:
- A running instance of FlowMQ.
- Node.js v14 or later installed.
npm
oryarn
for package management.
Installation
You can add MQTT.js
to your project using your preferred package manager.
# Using npm
npm install mqtt
# Or using yarn
yarn add mqtt
Connecting to FlowMQ
To get started, you need to connect to your FlowMQ broker. The mqtt.connect()
method returns a client instance.
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://localhost:1883', {
clientId: 'my-js-client'
});
client.on('connect', () => {
console.log('Connected to FlowMQ!');
// ... proceed to subscribe or publish
});
Subscribing to Topics
Once connected, you can subscribe to one or more topics to start receiving messages.
client.on('connect', () => {
console.log('Connected to FlowMQ!');
client.subscribe('flowmq/test', (err) => {
if (!err) {
console.log('Subscribed to flowmq/test');
// Now publish a message
client.publish('flowmq/test', 'Hello FlowMQ from MQTT.js!');
}
});
});
Receiving Messages
You can listen for the message
event on the client to process incoming messages from your subscriptions.
client.on('message', (topic, message) => {
// message is a Buffer
console.log(`Received message on topic ${topic}: ${message.toString()}`);
// Close the connection after receiving the message
client.end();
});
Full Example
Here is a complete Node.js script that connects, subscribes, publishes a message, and then handles the received message.
const mqtt = require('mqtt');
// Connect to the FlowMQ broker
const client = mqtt.connect('mqtt://localhost:1883', {
clientId: 'my-javascript-client'
});
// Handle the connect event
client.on('connect', () => {
console.log('Successfully connected to FlowMQ.');
// Subscribe to a topic
client.subscribe('flowmq/test/js', (err) => {
if (!err) {
console.log('Subscribed successfully!');
// Publish a message to the same topic
client.publish('flowmq/test/js', 'This is a test message from MQTT.js');
console.log('Message published.');
} else {
console.error('Subscription failed:', err);
}
});
});
// Handle incoming messages
client.on('message', (topic, message) => {
console.log(`Received message on topic '${topic}': ${message.toString()}`);
// End the client connection gracefully
client.end();
});
// Handle connection errors
client.on('error', (err) => {
console.error('Connection error:', err);
client.end();
});
Additional Resources
- For more advanced features, such as different QoS levels, retained messages, and browser usage, refer to the official MQTT.js repository.
- Explore FlowMQ's advanced features for MQTT.