MQTT communication protocol

MQTT(Message Queue Telemetry Transmission) is a lightweight publish-and-subscribe network protocol based on open OASIS and ISO standards. It can transmit messages between devices and is one of the most widely used communication protocols for the Internet of Things.

IBM developed the first version of MQTT protocol, which is lightweight, open, simple, standardized and easy to implement. These characteristics make it a good choice for many scenarios, especially for constrained environments such as machine-to-machine communication (M2M) and Internet of Things (IoT) environments.The figure includes the two roles in the MQTT protocol and the basic subscribe and publish patterns

  • broker/client

    A broker is a server that we build, and a client is a temperature sensor at each terminal or a laptop

  • Publish/subscribe

    A phone or computer client subscribes a Temp topic to the broker. When the temperature sensor client publishes a temp topic, the phone or computer receives the subscription

To build an MQTT Broker

The MQTT Broker uses Aedes for the build

const aedes = require('aedes') ()const server = require('net').createServer(aedes.handle)
const port = 18080

server.listen(port, function () {
    console.log('server started and listening on port ', port)
})
Copy the code

Test the MQTT Broker

Set up two clients to simulate and send temp every second. The client uses MQtt.js

  1. client_pub.js
var mqtt = require("mqtt")
var client = mqtt.connect("mqtt://localhost:18080")

// Publish temp topic continuously after connection
client.on("connect".(e) = > {
    console.log("success connect mqtt server");
    setInterval(() = > {
        client.publish("temp"."25.6")
        console.log("send it")},1000)})Copy the code
  1. client_sub.js
var mqtt = require("mqtt")
var client = mqtt.connect("mqtt://localhost:18080")

// Subscribe to Temp Topic after connecting
client.on('connect'.(e) = > {
  console.log("success connect mqtt server");
  client.subscribe('temp'.function (err) {
    console.log("subscribe temp topic")})})// Listen for messages for subscriptions
client.on('message'.function (topic, message) {
  // message is Buffer
  console.log(topic + ":\t" + message.toString())
})
Copy the code

Running both clients after starting the service yields the following results:

  1. The server
server started and listening on port  18080
Copy the code
  1. The client
# node mqtt-pub.js 
success connect mqtt server
send it
send it
send it
send it
send it
send it
send it
send it
send it
send it
send it

# node mqtt-sub.jsSuccess Connect MQTT Server SUBSCRIBE Temp Topic Temp: 25.6 temp: 25.6 temp: 25.6 temp: 25.6 temp: 25.6 temp: 25.6 25.6 Temp: 25.6 Temp: 25.6Copy the code

Welcome to my personal blog ximikang.icu