MQTT is a "lightweight" communication protocol based on the publish/subscribe model. The protocol is built on the TCP/IP protocol and was released by IBM in 1999. The biggest advantage of MQTT is that it can provide real-time and reliable messaging services for connecting remote devices with very few codes and limited bandwidth. As a low-overhead, low-bandwidth instant messaging protocol, it has a wide range of applications in the Internet of Things, small devices, and mobile applications.
1. Introduce mqtt
npm install mqtt -g
2. Use
1. Registration
var alias = Math.random().toString(16).substr(2, 8)
client = mqtt.connect(process.env.MQTT, { //注册地址
username: process.env.MQ_NAME, //注册mqtt 用户名
password: process.env.MQ_PD, //注册mqtt 密码
protocolVersion: 4,
protocolId: 'MQTT',
clientId: alias, // 要保证全局唯一
clean: true // 控制是否授受离线消息,false可以接受离线消息
})
2. Register the subject* (the subject mqtt sends the message to)
client.on('connect', function () {
client.subscribe(userName, function (err) {
if (!err) {
console.log('Hello mqtt')
client.publish('presence', 'Hello mqtt')
}
})
})
userName is the subject name (for example: username)
3. Accept the message
client.on('message', function (topic, message) {
// console.log(topic)
// console.log(message.toString())
msg = message
})
4. Close mqtt
client.on('end', function (err) {
client.end()
})
References ( https://github.com/mqttjs/MQTT.js#connect)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。