40 lines
1002 B
Markdown
40 lines
1002 B
Markdown
|
|
# leliven-mqtt
|
||
|
|
|
||
|
|
## 使用
|
||
|
|
1. 依赖 [leliven-mqtt](https://ext.dcloud.net.cn/plugin?name=leliven-mqtt)
|
||
|
|
3. 页面引用 ` import mqtt from '@/uni_modules/leliven-mqtt/index.js'`
|
||
|
|
4. 详细使用说明:[MQTT.js](https://github.com/mqttjs/MQTT.js)
|
||
|
|
|
||
|
|
```js
|
||
|
|
|
||
|
|
// 初始化客户端连接地址
|
||
|
|
// #ifdef H5
|
||
|
|
let client = mqtt.connect('ws://test.mosquitto.org:8080')
|
||
|
|
// #endif
|
||
|
|
// #ifdef MP-WEIXIN||APP-PLUS
|
||
|
|
let client = mqtt.connect('wx://test.mosquitto.org:8080')
|
||
|
|
// #endif
|
||
|
|
|
||
|
|
// 连接MQ服务
|
||
|
|
client.on('connect', function() {
|
||
|
|
console.log('连接成功')
|
||
|
|
|
||
|
|
// 订阅主题
|
||
|
|
client.subscribe('presence', function(err) {
|
||
|
|
if (!err) {
|
||
|
|
// 订阅成功
|
||
|
|
client.publish('presence', 'hello mqtt')
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}).on('reconnect', function() {
|
||
|
|
console.log('重新连接')
|
||
|
|
}).on('error', function() {
|
||
|
|
console.log('连接失败')
|
||
|
|
}).on('end', function() {
|
||
|
|
console.log('连接End')
|
||
|
|
}).on('message', function(topic, message) {
|
||
|
|
// 收到MQ消息
|
||
|
|
console.log(message.toString())
|
||
|
|
})
|
||
|
|
|
||
|
|
```
|