vue3和mqqt的的连接
在vue3项目中引入 mpn intall mqtt -S
然后还要引入:
npm install node-polyfill-webpack-plugin
//头部引用
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
//加入
configureWebpack: {
plugins: [new NodePolyfillPlugin()]
}
//封装一个类(可直接cv)
import mqtt from 'mqtt'
class createds {
//创建公共变量
static url; //mqtt地址
static oldSubscribe; //取消订阅准备
static subscribe; //订阅地址
static client; //mqtt公共变量
//接受床底来的数据
constructor(subscribe) {
console.log(subscribe, "订阅地址");
//获取传递来的订阅地址
this.subscribe = subscribe;
this.url = "ws://1.15.180.124:8083/mqtt";
}
//初始化mqtt
init() {
const options = {
clean: true, // true: 清除会话, false: 保留会话
connectTimeout: 4000, // 超时时间
// username: "xxx",
// password: "xxxx",
cleanSession : false,
keepAlive:60,
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
};
this.client = mqtt.connect(this.url, options);
this.client.on("error", (error) => {
console.log(error);
});
this.client.on("reconnect", (error) => {
console.log(error);
});
}
//取消订阅
unsubscribes() {
this.client.unsubscribe(this.subscribe, (error) => {
if (!error) {
console.log(this.subscribe, "取消订阅成功");
} else {
console.log(this.subscribe, "取消订阅失败");
}
});
}
publish(topic,message) {
if (!this.client.connected) {
console.log('客户端未连接')
return
}
this.client.publish(topic,message,{qos: 1},(err) => {
if(!err) {
console.log('主题为'+topic+ "发布成功")
console.log(message)
}
})
}
//结束链接
over() {
this.client.end();
}
//链接
link() {
this.client.on("connect", (e) => {
console.log(e)
this.client.subscribe(this.subscribe, (error) => {
//在js代码中最简单的抛出异常方法
if (!error) {
console.log("订阅成功");
} else {
console.log("订阅失败");
}
});
});
}
//收到的消息
get() {
this.client.on("message", (topic, message) => {
console.log("收到消息:", message.toString());
});
}
//结束链接
}
export default createds;
const PublicMqtt = ref(null);
const startMqtt = (val) => {
//val = 订阅地址
//设置订阅地址
PublicMqtt.value = new createds(val);
//初始化mqtt
PublicMqtt.value.init();
//链接mqtt
PublicMqtt.value.link();
getMessage();
};
//获取订阅数据
const getMessage = () => {
PublicMqtt.value.client.on("message", (topic, message) => {
let str = JSON.parse(message.toString());
console.log(topic);
console.log(str,'返回的数据')
});
};
const putMessage =(topic,message)=>{
PublicMqtt.value. publish(topic,message);
};
//取消MQTT订阅
const unsubscribe = () => {
//如果页面并没有初始化MQTT,无需取消订阅
if (PublicMqtt.value) {
PublicMqtt.value.unsubscribes();
}
};
onUnmounted(() => {
//页面销毁结束订阅
if (PublicMqtt.value) {
PublicMqtt.value.unsubscribes();
PublicMqtt.value.over();
}
});
return{
startMqtt,
putMessage,unsubscribe
}
}
}
etMessage() { this.client.on("message", (topic, message) => { if(message) { console.log('收到来着',topic,'的信息',message.toString()) const res = JSON.parse(message.toString()) //console.log(res, 'res') switch(topic) { case 'top/#' : this.msg = res break; case 'three/#' : this.msg = res break; case 'three/#' : this.msg = res break; default: return this.msg = res } this.msg = message } }); },
this.client.subscribe(['top/#', 'three/#', '#'], { qos: 1 }, (err)=> { if (!err) { console.log("订阅成功"); //向主题叫“pubtop”发布一则内容为'hello,this is a nice day!'的消息 this.publish("pubtop", 'hello,this is a nice day!') } else { console.log('消息订阅失败!') } });