1

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.
image.png

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)


三月
425 声望105 粉丝

街市人如鲫,晤君当有期,阴晴岁月稠,黯然眠中泣,相逢属不易,缘定自珍惜。