1、在微信小程序中使用MQTT.JS,版本为4.2.0,https://cdnjs.com/libraries/mqtt/4.2.0
只要一发布消息就断开连接,只有第一次能够成功发布消息,后面就一直提示如下图错误。
initialMqtt:function()
{
//连接配置
const options = {
connectTimeout: config.mqtt.connectTimeout, //超时时间
// port: 8083,
clientId: util.random(32), //随机生成ID
username: config.mqtt.userName, //用户名
password: config.mqtt.password, //密码
}
var schoolId = app.userinfo.baseinfo.SchoolId;
var topicName = "realdata/alarmdata/#";
var client = mqtt.connect(config.mqtt.host, options)
client.on('connect', (e) => {
console.log('成功连接服务器!');
client.subscribe(topicName, { qos: 0}, function (err) {
if (!err) {
console.log("订阅成功:"+topicName)
}
})
// var sendMsg = JSON.stringify("{'hello':'mqtt'}")
// client.publish(topicName, sendMsg, { qos: 0}, function (e) {
// console.log('发布消息'+"{'hello':'mqtt'}")
// });
app.clientMqtt = client;//将Mqtt客户端存储成全局变量
client.on('message', function (topic, message, packet) {
var array = topic.split('/');
var equipCode = array.length > 0 ? array[array.length-1] : "";
})
})
client.on('disconnect', () => {
console.log('代理断开连接');
});
client.on('close', () => {
console.log('断开连接');
});
client.on('offline', () => {
console.log('脱机');
});
client.on('error', () => {
console.log('无法连接');
this.initialMqtt();
});
},
参考一下:https://developers.weixin.qq.com/community/develop/doc/0008e6a0494e18415fbac631d51c00?_at=1667133023444