<template>
<view class="page-main">
<button type="default" @click="publish()" v-if="connected">发布MQTT消息</button>
<button type="default" @click="connectMqtt()" v-else>连接MQTT</button>
</view>
</template>
<script>
let mqtt = require('../../lib/mqtt.min.js')
export default {
data() {
return {
client: null,
connected: false,
testTopic: 'myTopic', //作为测试订阅的主题
};
},
methods: {
connectMqtt() {
uni.showLoading({
title: '正在连接',
mask: true
})
let username = uni.getSystemInfoSync().deviceId;
let password = uni.getSystemInfoSync().deviceId;
this.client = mqtt.connect(`wx://api.easylink.io/mqtt`, {
port: 1983,
keepalive: 10,
protocolId: 'MQTT',
protocolVersion: 4,
connectTimeout: 5000,
clientId: username,
username: username,
password: password,
});
// 监听MQTT连接成功回调
this.client.on('connect', (e) => {
// MQTT服务链接成功
console.log('MQTT连接成功==', e);
uni.hideLoading();
uni.showToast({
title: '连接成功'
})
this.connected = true
// 订阅一个主题topic用于测试
this.client.subscribe(this.testTopic)
});
// 监听MQTT消息回调
this.client.on('message', (topic, payload) => {
payload = payload.toString()
console.log('收到自身订阅的测试主题消息==', payload);
uni.showModal({
title: '收到MQTT消息',
content: payload,
showCancel: false
})
});
// 监听MQTT重连回调
this.client.on('reconnect', (e) => {
uni.hideLoading()
uni.showLoading({
title: '正在连接',
mask: true
})
this.connected = false
console.log('[Mqtt]=> Reconnect:', e);
});
// 监听MQTT离线回调
this.client.on('offline', (e) => {
uni.hideLoading();
this.connected = false
console.log('[Mqtt]=> Offline:', e);
});
},
publish() {
let payload = new Date().toLocaleString() //发布的MQTT消息
this.client.publish(this.testTopic, payload)
}
}
};
</script>
- 发布:2023-01-29 00:37
- 更新:2023-01-30 11:32
- 阅读:189
产品分类: HbuilderX
PC开发环境操作系统: Windows
PC开发环境操作系统版本号: windows10
HBuilderX版本号: 3.6.18
示例代码:
操作步骤:
在3.6.18版本中运行实例demo到手机上,点击“连接MQTT”,此时无法连接成功。退回3.6.15版本重新运行实例demo,mqtt正常连接并能正常发布MQTT消息
在3.6.18版本中运行实例demo到手机上,点击“连接MQTT”,此时无法连接成功。退回3.6.15版本重新运行实例demo,mqtt正常连接并能正常发布MQTT消息
预期结果:
在最新版本HBuilderX上能正常连接MQTT
在最新版本HBuilderX上能正常连接MQTT
实际结果:
在最新版本HBuilderX上无法正常连接MQTT
在最新版本HBuilderX上无法正常连接MQTT
bug描述:
在3.6.17和3.6.18版本,APP使用MQTT连接不上,退回3.6.15版本正常。在论坛看到同样的问题:
https://ask.dcloud.net.cn/question/161631