Introduction
MQTT.js is an open source MQTT protocol client library, written in JavaScript, mainly used in Node.js and browser environments. MQTT client library that is most widely used in the JavaScript ecosystem.
MQTT is a lightweight IoT messaging protocol based on the publish/subscribe model. It can provide real-time and reliable messaging services for networked devices with very little code and bandwidth. It is widely used in the Internet of Things, mobile Internet, smart hardware, The Internet of Vehicles, electric power and other industries.
Due to the single-threaded feature of JavaScript, MQTT.js is a fully asynchronous MQTT client. MQTT.js supports MQTT/TCP, MQTT/TLS, MQTT/WebSocket, and the degree of support in different operating environments is as follows:
- Browser environment: MQTT over WebSocket (including custom browser environments such as WeChat applet and Alipay applet)
- Node.js environment: MQTT, MQTT over WebSocket
In different environments, except for a few connection parameters, other APIs are the same. And after MQTT.js v3.0.0 and above, MQTT 5.0 has been fully supported.
Install
Install using npm or yarn
npm install mqtt --save
# 或使用 yarn
yarn add mqtt
Note : If your Node environment is v12 or v14 and above, please use MQTT.js 4.0.0 and above
Install using CDN
In the browser environment, we can also use CDN to introduce MQTT.js. The bundle package of http://unpkg.com 16139ccb04adb2, we can directly add unpkg.com/mqtt/dist/mqtt.min.js to use.
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
// 将在全局初始化一个 mqtt 变量
console.log(mqtt)
</script>
Global installation
In addition to the above installation methods, MQTT.js also provides a global installation method, using command-line tools to complete MQTT connection, publishing, and subscription.
npm install mqtt -g
We will describe in detail how to use the command line tool of MQTT.js in some tutorials below.
use
This article will use the free public MQTT server provided by EMQ X Cloud as the MQTT server address for this test. The server access information is as follows:
- Broker: broker.emqx.io
- TCP Port: 1883
- SSL/TLS Port: 8883
For more details, please visit EMQ X Cloud official website , or check EMQ X Cloud document .
Simple example
We simply write a piece of code to connect to EMQ X Cloud and complete an example of subscribing to topics and sending and receiving messages:
const mqtt = require('mqtt')
const options = {
// Clean session
clean: true,
connectTimeout: 4000,
// Auth
clientId: 'emqx_test',
username: 'emqx_test',
password: 'emqx_test',
}
const client = mqtt.connect('mqtt://broker.emqx.io:1883')
client.on('connect', function () {
console.log('Connected')
client.subscribe('test', function (err) {
if (!err) {
client.publish('test', 'Hello mqtt')
}
})
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
Command Line
After installing MQTT.js globally, we can also use the command line tool to complete the topic subscription message publishing and receiving actions.
The example connects to broker.emqx.io
and subscribes to the topic testtopic/#
mqtt sub -t 'testtopic/#' -h 'broker.emqx.io' -v
The example connects to broker.emqx.io
and sends a message to the testtopic/hello
mqtt pub -t 'testtopic/hello' -h 'broker.emqx.io' -m 'from MQTT.js'
API introduction
mqtt.connect([url], options)
Connect to the specified MQTT Broker function and always return a Client object. The first parameter is passed in a URL value, the URL can be the following protocol: mqtt
, mqtts
, tcp
, tls
, ws
, wss
. URL can also be an object returned by URL.parse(). Then pass in an Options object to configure the options of the MQTT connection. Here are some commonly used attribute values in the Options object:
Options
keepalive
: The unit isseconds, numeric type, the default is 60 seconds, and it is disabled when set to 0
clientId
: The default is'mqttjs_' + Math.random().toString(16).substr(2, 8)
, which can support custom modified stringsprotocolVersion
: MQTT protocol version number, the default is 4 (v3.1.1) and can be modified to 3 (v3.1) and 5 (v5.0)clean
: The default istrue
, whether to clear the session. When set totrue
, the session will be cleared after disconnection, and the subscribed Topics will also become invalid. When set tofalse
, messages with QoS 1 and 2 can also be received in offline statereconnectPeriod
: Reconnection interval time, the unit is milliseconds, the default is 1000 milliseconds, Note: set to 0, automatic reconnection will be cancelledconnectTimeout
: Connection timeout duration, the waiting time before receiving CONNACK, in milliseconds, the default is 30000 millisecondsusername
: Authentication user name, if Broker requires user name authentication, please set this valuepassword
: Authentication password, if Broker requires password authentication, please set this valuewill
: Will message, a configurable object value. When the client disconnects abnormally, the Broker will publish a message to the Will Topic in the format:topic
: Topic sent by the willpayload
: News from the willQoS
: QoS value sent by the willretain
: The retain sign of the message published in the will
properties
: MQTT 5.0 new, configurable object property values, please refer to: https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
If you need to configure an SSL/TLS connection, the Option object will be passed to
tls.connect()
, so you can configure the following properties in optionrejectUnauthorized
: Whether to verify the server certificate chain and address name. When set to false, the verification will be skipped and will be exposed to man-in-the-middle attacks. Therefore, it is not recommended to use this configuration in a production environment. When set to true, it will be enabled Strong authentication mode, and if it is a self-signed certificate, please set Alt name during certificate configuration.ca
: Only necessary when the server uses a self-signed certificate, the CA file generated in the self-signed certificate- cert: Only necessary when the server requires client certificate authentication (two-way authentication), client certificate
- key: Only necessary when the server requires client certificate authentication (two-way authentication), the client key
Client events
When the connection is successful, the returned Client object can listen to multiple events through the on method, and the business logic can be completed in the listener callback function. Here are some common events:
connect
Triggered when the connection is successful, the parameter is connack
client.on('connect', function (connack) { console.log('Connected') })
reconnect
Triggered when the connection is automatically reconnected to the Broker after the reconnection interval has elapsed after disconnection
client.on('reconnect', function () { console.log('Reconnecting...') })
close
Triggered after disconnection
client.on('close', function () { console.log('Disconnected') })
disconnect
Triggered when a disconnected message sent by Broker is received, the parameter packet is the message received when disconnected, the function in MQTT 5.0
client.on('disconnect', function (packet) { console.log(packet) })
offline
Triggered when the client goes offline
client.on('offline', function () { console.log('offline') })
error
Triggered when the client cannot connect successfully or a parsing error occurs, the parameter error is the error message
client.on('error', function (error) { console.log(error) })
message
Triggered when the client receives a published payload, which contains three parameters, topic, payload and packet, where topic is the topic of the received message, payload is the content of the received message, and packet is the MQTT message information. It contains QoS, retain and other information
client.on('message', function (topic, payload, packet) { // Payload is Buffer console.log(`Topic: ${topic}, Message: ${payload.toString()}, QoS: ${packet.qos}`) })
Client method
In addition to monitoring events, Client also has some built-in methods for publishing and subscribing operations. Here are some commonly used methods.
Client.publish(topic, message, [options], [callback])
A function method to publish a message to a topic, which contains four parameters:
- topic: the topic to be sent, as a string
- message: The message under the subject to be sent, which can be a string or a Buffer
- options: Optional value, configuration information when publishing a message, mainly to set the QoS and Retain value when publishing a message.
- callback: the callback function after the message is published, the parameter is error, this parameter only exists when the publication fails
// 向 testtopic 主题发送一条 QoS 为 0 的测试消息 client.publish('testtopic', 'Hello, MQTT!', { qos: 0, retain: false }, function (error) { if (error) { console.log(error) } else { console.log('Published') } })
Client.subscribe(topic/topic array/topic object, [options], [callback])
The method of subscribing to one or more topics. When the connection is successful, you need to subscribe to the topic to get the message. This method contains three parameters:
- topic: You can pass in a string, or an array of strings, or a topic object,
{'test1': {qos: 0}, 'test2': {qos: 1}}
- options: optional value, configuration information when subscribing to Topic, mainly to fill in the QoS level of the subscribed Topic
- callback: callback function after subscribing to Topic. The parameters are error and granted. The error parameter only exists when the subscription fails. Granted is an array of {topic, qos}, where topic is a subscribed topic, and qos is a topic that is granted QoS level
// 订阅一个名为 testtopic QoS 为 0 的 Topic client.subscribe('testtopic', { qos: 0 }, function (error, granted) { if (error) { console.log(error) } else { console.log(`${granted[0].topic} was subscribed`) } })
- topic: You can pass in a string, or an array of strings, or a topic object,
Client.unsubscribe(topic/topic array, [options], [callback])
To unsubscribe a single topic or multiple topics, this method contains three parameters:
- topic: You can pass in a string or an array of strings
- options: Optional value, configuration information when unsubscribing
- callback: callback function when unsubscribing, the parameter is error, the error parameter only exists when unsubscribing fails
// 取消订阅名为 testtopic 的 Topic client.unsubscribe('testtopic', function (error) { if (error) { console.log(error) } else { console.log('Unsubscribed') } })
Client.end([force], [options], [callback])
Close the client, this method contains three parameters:
- force: When set to true, the client will be shut down immediately without waiting for the disconnected message to be accepted. This parameter is optional and the default is false. Note : When this value is true, the Broker cannot receive the disconnect message
- options: Optional value, configuration information when the client is closed, mainly reasonCode can be configured, Reason Code when disconnected
- callback: callback function when the client is closed
client.end()
Summarize
So far, I briefly introduced the usage of some commonly used APIs of MQTT.js, etc. For specific usage in actual projects, please refer to the following link:
- How to use MQTT in Vue project
- How to use MQTT in React project
- How to use MQTT in Electron project
- How to use MQTT in Node.js project
- Use WebSocket to connect to MQTT server
Copyright statement: This article is EMQ original, please indicate the source for reprinting.
Original link: https://www.emqx.com/zh/blog/mqtt-js-tutorial
Technical support: If you have any questions about this article or EMQ related products, you can visit the EMQ Q&A community https://askemq.com ask questions, and we will reply to support in time.
For more technical dry goods, please pay attention to our public account [EMQ Chinese Community].
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。