前文写了使用Docker部署了mqtt服务,今天来写一下,mqtt在web开发中的应用实例,希望能帮到大家,话不多说,直接开始。
作者这里用的vue3的框架
直接上命令,npm安装或者pnpm进行安装。
npm install mqtt
1.创建一个mqtt封装的js文件
比如我创建一个mqttTool.js
2.在js文件中引入mqtt
import * as mqtt from 'mqtt/dist/mqtt.min.js';
3.封装全局服务
const getMQTTUrl = () =>{
let url = import.meta.env.VITE_APP_PHAR_MQTT;
url ='ws://0.0.0.0:8000/mqtt'; //填写自己的mqtt服务ip
console.info("当前 MQTT 地址为 " + url);
return url
}
//MQTT全局服务
export default class MQTTService {
static instance = null;
static get Instance() {
if (!this.instance) {
this.instance = new MQTTService();
}
return this.instance;
}
// 事件
mitt = new mitt();
//配置参数
userOptions= {
username: "mqttName",
password: "test123",
clientId: Math.random().toString(36).substr(2),
};
topics = [];//["test1", "dtest2"]; //需要订阅的主题
// 和服务端连接的MQTT对象
client = null;
mqttUrl = getMQTTUrl() ;
// 标识是否连接成功
connected = false;
// 记录重试的次数
sendRetryCount = 0;
// 重新连接尝试的次数
connectRetryCount = 3;
// 再次连接
reconnect(){
if (this.client==null){
this.connect()
}
}
//定义连接服务器的方法
connect() {
let that =this;
this.client = mqtt.connect(this.mqttUrl, this.userOptions);
this.client.on("connect", (e) => {
this.connected = true;
// 重置重新连接的次数
this.connectRetryCount = 3;
that.topics.forEach((topic) => {
that.client.subscribe(
topic,
{ qos: 0, retain: 0 },
(err, granted) => {
if (granted.length > 0) {
if (!err) {
console.log(`全局成功订阅主题:${granted[0].topic}`);
} else {
console.log("全局订阅主题失败", err);
}
}
}
);
});
});
//失败重连
this.client.on('error', (e) => {
if (this.sendRetryCount < this.connectRetryCount-1){
console.log("连接服务端失败:",e)
this.connected = false;
this.sendRetryCount++
setTimeout(() => {
this.connect();
}, 500 * this.connectRetryCount);
}
});
this.client.on("message", (topic, message, packet) => {
// 输出订阅的主题和消息
console.log(`接收到主题为 ${topic} 的消息:`, message.toString());
let res ={
topic:topic,
message:message,
packet:packet
}
});
}
close(){ // 退出登录后断开连接
if (this.client) {
this.client.end(); //离开页面的时候 关闭mqtt连接
this.client = null;
console.log("关闭mqtt:");
}
}
// 发送数据的方法
send(data) {
// 判断此时此刻有没有连接成功
if (this.connected) {
this.sendRetryCount = 0;
try {
this.client.publish(data.sender, data);
console.log("s发送到服务端:",data);
} catch (e) {
this.client.publish(data.sender, JSON.stringify(data)); console.log("O发送到服务端:",data)
}
} else {
this.sendRetryCount++;
setTimeout(() => {
this.reconnect() // 重新连接
this.client.publish(data.sender, JSON.stringify(data));
}, this.sendRetryCount * 500);
}
}
// 发送数据的方法2
sendBySender(sender,data) {
// 判断此时此刻有没有连接成功
if (this.connected) {
this.sendRetryCount = 0;
try {
this.client.publish(sender, data);
console.log("s发送到服务端:",data)
} catch (e) {
this.client.publish(sender, JSON.stringify(data)); console.log("O发送到服务端:",data)
}
} else {
this.sendRetryCount++;
setTimeout(() => {
this.reconnect() // 重新连接
this.client.publish(sender, JSON.stringify(data));
}, this.sendRetryCount * 500);
}
}
//自定义订阅内容
setTopics(data){
this.topics = data;
this.close();
this.connect();
}
getTopics(){
return this.topics;
}
//添加订阅
addTopic(topic){
this.topics.push(topic);
if (this.connected) {
this.client.subscribe(
topic,
{ qos: 0, retain: 0 },
(err, granted) => {
if (granted.length > 0) {
if (!err) {
console.log(`全局成功订阅主题:${granted[0].topic}`);
} else {
console.log("全局订阅主题失败", err);
}
}
}
);
}else{
this.connect();
}
}
}
4.调用
在需要的vue中调用
import MQTTService from '/@/utils/mqttTool.js'
let mqttServe = MQTTService.Instance;
然后使用mqttServe对象调用相关方法即可。