How to Build a Bi‑directional MQTT Sensor Network with Node.js
This article outlines the background, terminology, network architecture, and step‑by‑step Node.js implementation of both MQTT broker and client for a sensor project, enabling two‑way communication between cloud platforms and edge devices without fixed IPs, complete with code snippets and visual results.
1. Project Background
Company collaborates with a third party to develop a sensor project that can be controlled via computer or mobile phone. Because edge terminals connect to the public network wirelessly and cannot obtain a fixed IP, conventional HTTP communication is infeasible, so MQTT is chosen for bidirectional communication between the cloud platform and edge terminals.
2. Terminology
2.1 Cloud Platform
Software system deployed in the cloud for managing data and devices, interacting with edge terminals to acquire data or issue commands.
2.2 Edge Terminal
Computing device at the network edge that connects to the cloud platform and downstream to analyzers and sensors.
2.3 Analyzer
Device that receives data, connecting to edge terminals or, via wired mode, receiving sensor data from various sources.
2.4 Sensor
Device that connects to the edge terminal via wired or wireless mode to transmit parameters, or connects to the analyzer via wired mode.
3. Network Architecture
4. Code Implementation
4.1 Server Implementation
First install Node.js and the Aedes MQTT broker; installation steps are widely available.
Create a file named "server.js".
const aedes = require('aedes')();
const aedesServer = require('net').createServer(aedes.handle);
const port = 1883;
aedesServer.listen(port, function () {
console.log('服务启动并开始监听端口:', port);
});
// Listen for client connections
aedes.on("client", (client) => {
console.log("客户端连接成功:", client.id);
});
// Listen for client disconnects or missing heartbeat
aedes.on("clientDisconnect", (client) => {
console.log("客户端断开连接:", client.id);
});
// Listen for published topics
aedes.on("publish", function (packet, client) {
if (client) {
console.log("监听客户端发过来的消息", packet.topic, packet.payload.toString());
}
});
// Server publishes messages periodically
setInterval(() => {
aedes.publish({
topic: "serverMsg",
payload: "服务器发消息",
qos: 1,
retain: false,
dup: false,
cmd: "publish"
}, (err) => {
if (err) {
console.log("发布失败");
}
});
}, 20000);4.2 Client Implementation
Create a file named "client.js".
The client uses mqtt.connect to establish a long‑lived connection with the server.
In practice the client may occasionally disconnect and reconnect; stability needs verification.
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://192.168.70.220:1883', {
clientId: 'nodejs-mqtt-client'
});
client.on('connect', function () {
console.log('连接上MQTT服务器');
client.subscribe('serverMsg', { qos: 1 });
});
setInterval(() => {
client.publish('topic1', 'hello mqtt client', { qos: 1 });
}, 20000);
client.on('message', function (topic, message) {
console.log('接受服务器消息:', '主题:', topic, '消息:', message.toString());
});4.3 Result Presentation
Two timers achieve bidirectional communication.
Server side:
Client side:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
