import Stomp from "stompjs";
import { ElMessage } from "element-plus";
import globalEvent from "@/utils/globalEvent";
class Socket {
// socket 对象
client;
config;
constructor(config) {
this.config = config;
// this.init();
}
numberOfRetries = 0;
// 启动socket
init() {
const config = this.config;
this.client = Stomp.client(this.config.socket.MQTT_SERVICE);
//初始化mqtt客户端,并连接mqtt服务
const headers = {
login: this.config.socket.MQTT_USERNAME,
passcode: this.config.socket.MQTT_PASSWORD,
};
this.client.connect(
headers,
function () {debugger
const topic = config.socket.topic;
this.subscribe(
topic,
(frame) => {debugger
globalEvent.$emit("rmqGetActionMenu", frame.body);
},
(frame) => console.log("socket 订阅失败 ", frame)
);
},
(frame) => {debugger
console.error("socket 连接失败 ", frame);
if (this.numberOfRetries % 5 === 0)
ElMessage.warning("网络不稳定,请稍后");
if (this.numberOfRetries === 0) {
this.numberOfRetries++;
this.init();
} else {
setTimeout(() => {
this.numberOfRetries++;
this.init();
}, 3000);
}
}
);
}
}
export default Socket;