安装(使用最新版本的mqtt连接有些问题)
npm i mqtt@3.0.0 --save
const mqtt = require('mqtt/dist/mqtt.js')
// 获取终端标识
var pinf = plus.push.getClientInfo();
var clientId = pinf.clientid; //客户端标识
// 连接选项
const options = {
clean: true, // 保留回话
connectTimeout: 4000, // 超时时间
// 认证信息
clientId,
username: 'admin',
password: 'public',
topic: 'testtopic'
}
// 连接字符串, 通过协议指定使用的连接方式
// ws 未加密 WebSocket 连接
// wss 加密 WebSocket 连接
// mqtt 未加密 TCP 连接
// mqtts 加密 TCP 连接
// wxs 微信小程序连接
// alis 支付宝小程序连接
// #ifdef H5
const connectUrl = 'ws://test.mosquitto.org:8080'
// #endif
// #ifdef MP-WEIXIN||APP-PLUS app端需要使用wx
const connectUrl = 'wx://test.mosquitto.org:8080'
// #endif
const client = mqtt.connect(connectUrl, options)
client.on('connect', function(mes) {
// 订阅
client.subscribe("testtopic");
})
client.on('reconnect', (error) => {
console.log('正在重连:', error)
})
client.on('error', (error) => {
console.log('连接失败:', error)
})
client.on('message', (topic, message) => {
console.log('收到消息:', topic, message.toString())
})