##uniapp_微信小程序_mqtt封装以及必能用版本
用来总结和学习,便于自己查找
文章目录
一、下载mqtt版本,以及相关问题?
二、mqtt代码封装?
2.1 使用代码封装?
一、下载mqtt版本,以及相关问题?
不多废话直接上能用的版本,先说一下之前的3.0.0版本只能在开发者工具使用,真机还有体验版本都不行,找
问题头都大了,换成最新的5点几版本也不行,最后找到4.1.0就可以了
npm i mqtt@4.1.0
二、mqtt代码封装?
import mqtt from 'mqtt/dist/mqtt';
// import * as mqtt from 'mqtt/dist/mqtt'; // 直接使用 *
class MQTT {
constructor({
clientId, cleanSession = false, keepAlive = 60 }) {
this.url = 'wxs://mqtt.zh-zhsq.com:8084/mqtt'; // 写死的 URL
this.clientId = clientId;
this.username = 'zhylqsd'; // 写死的用户名
this.password = 'zhylqsd~~@@abc'; // 写死的密码
this.cleanSession = cleanSession; // 默认值
this.keepAlive = keepAlive; // 默认值
this.client = null;
}
// 初始化 MQTT
init() {
const options = {
clean: this.cleanSession, // 使用 cleanSession 设置
clientId: this.clientId,
username: this.username, // 使用写死的用户名
password: this.password, // 使用写死的密码
connectTimeout: 4000, // 超时时间
keepalive: this.keepAlive, // 使用 keepAlive 设置
};
this.client = mqtt.connect(this.url, options);
this.client.on('connect', () => {
console.log("连接成功",this.client);
});
this.client.on('error', (error) => {
console.error('MQTT连接错误:', error);
});
this.client.on('reconnect', (error) => {
console.log('正在重新连接:', error,this.client);
});
}
// 订阅主题
subscribe(topic) {
this.client.subscribe(topic, (error) => {
if (!error) {
console.log(`已订阅新主题111: ${
topic}`);
} else {
console.log(`订阅失败: ${
topic}`, error);
}
});
}
// 取消订阅
unsubscribe(topic) {
this.client.unsubscribe(topic, (error) => {
if (!error) {
console.log(`已取消订阅11111: ${
topic}`);
} else {
console.log(`取消订阅失败: ${
topic}`, error);
}
});
}
// 接收消息
get(callback) {
this.client.on('message', callback);
}
// 断开连接
over() {
if(this.client){
this.client.end();
console.log("断开mqtt连接");
}
}
}
export default MQTT;
2.1 使用代码封装?
import MQTT from '../../pagesMy/utils/mqtt.js';//引入先
reconnctmqtt() {
// 配置 MQTT 参数
this.mqttClient = new MQTT({
clientId: "zhyl_" + this.res.Ext.privatekey,
});
this.mqttClient.init();
const defaultTopic= this.res.Ext.privatekey
this.mqttClient.subscribe(defaultTopic);
// 接收消息,使用回调函数处理
this.mqttClient.get((topic, message) => {
console.log(`收到来自 ${
topic} 的消息:`, JSON.parse(message.toString()));
});
},
beforeDestroy() {
const privatekey = this.res.Ext.privatekey
const defaultTopic1 = `zh-ylgl/zhylqsd/${
privatekey}/${
this.bedid}`;
this.mqttClient.unsubscribe(defaultTopic1)
this.mqttClient.over()
},
init连接然后订阅最后 接收消息,使用回调函数处理就调用封装的就行,重要的是mqtt版本切记
切记!!!!!!!!!!!!!