安装插件
npm install mqtt --save
、
设置(后台帮助订阅topic)
import { GlobalStore } from "@/store";
import mqtt, { IConnectPacket, MqttClient, Packet } from "mqtt";
import { computed } from "vue";
export interface MqttMsgHander {
(message: string): void;
}
export default class MqttService {
static BASE_URL = "xxxx";
private static instance: MqttService = new MqttService();
public static getInstance(): MqttService {
return MqttService.instance;
}
// 客户端id
static CLIENTID = computed(
() => `${GlobalStore.getInstance().userMess.username}_web`
);
private listener: Map<string, Array<MqttMsgHander>> = new Map();
private mqtt: MqttClient | null = null;
token = computed(
() =>
sessionStorage.getItem("accessToken") ||
localStorage.getItem("accessToken")
);
connect(username: string) {
const option = {
clientId: `${username}_web`,
username: username,
password: this.token.value!,
keepalive: 60,
clean: true,
reconnectPeriod: 1000
};
this.mqtt = mqtt.connect(MqttService.BASE_URL, option);
this.mqtt.once("connect", (topic: IConnectPacket) => {
this.connectionOkHandler();
});
}
disconnection() {
this.mqtt!.end(true);
}
sendMsg(topic: string, mess: string) {
return new Promise((resolve, reject) => {
this.mqtt!.publish(topic, mess, (err?: Error, tas?: Packet) => {
if (err) {
reject(err);
} else {
resolve(0);
}
});
});
}
connectionOkHandler() {
this.mqtt!.on("message", (topic: string, message: any, packet: any) => {
const sub = this.listener.get(topic);
if (sub) {
sub.forEach(sub => {
sub(message);
});
}
});
}
regirest(topic: string, handler: MqttMsgHander) {
let handlers = this.listener.get(topic);
if (!handlers) {
handlers = new Array<MqttMsgHander>();
this.listener.set(topic, handlers);
}
handlers.push(handler);
}
unregist(topic: string, handler: MqttMsgHander) {
const handlers = this.listener.get(topic);
if (handlers) {
const index = handlers.indexOf(handler);
if (index > -1) {
handlers.splice(index, 1);
}
}
}
}
登录Mqtt
MqttService.getInstance().connect(username!);
使用
this.mqttInstance.regirest(
this.topicMess.value.topic,
this.receptionMessage
);
receptionMessage = (message?: any) => {
const res = JSON.parse(message.toString());
this.handleAvatar(res);
this.modal.messageList.push(this.handleMess(res, false));
};