【IoT】Node.js MQTT Demo

Posted by 西维蜀黍 on 2018-11-24, Last Modified on 2024-05-07

Setup MQTT Server

If you want to run your own MQTT broker (MQTT Server), you can use Mosquitto or Mosca, and launch it.

Take mosca as an example:

Install mosca:

npm install mosca --save

Server code:

var mosca = require("mosca");
var server = new mosca.Server({
  http: {
    port: 3000,
    bundle: true,
    static: './'
  }
});

// fired when a new client connects
server.on('clientConnected', function(client) {
    console.log('client (clientId:', client.id, ') connected');
});

// fired when a message is received
server.on('published', function(packet, client) {
  	console.log("-------------------------------");
  	console.log('Published', packet.payload);
  	console.log("-------------------------------");
});

server.on('ready', setup);

// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running');
}

Setup Publisher

Install mqtt:

npm install mqtt --save

Publisher Code:

var mqtt = require('mqtt')
var client  = mqtt.connect([{ host: 'localhost', port: 3000 }])

client.on('connect', function () {
	client.publish('topic1', "Hello topic1!!!")
	// setInterval(function(){ 
	// 	client.publish('topic1', "Hello topic1!!!")
 //  	 }, 10000);
});

client.on('message', function (topic, message) {
	// message is Buffer
	console.log(message.toString());
});

Setup Subscriber

var mqtt = require('mqtt')
var client  = mqtt.connect([{ host: 'localhost', port: 3000 }])

client.on('connect', function () {
  	client.subscribe('topic1', function (err) {
 	 });
});

client.on('message', function (topic, message) {
	// message is Buffer
	console.log(message.toString());
});

Note that all the source code can be downloaded from https://github.com/swsmile/MQTTDemoInNode.

Package Analysis

If we use Wireshark to capture the MQTT package, the whole interaction process will be very clear.

Using MQTT Over WebSockets

http://www.steves-internet-guide.com/mqtt-websockets/

https://www.youtube.com/watch?v=EvUI4vRhF88&feature=youtu.be

http://www.steves-internet-guide.com/using-javascript-mqtt-client-websockets/

Reference