Files
aida_front/src/tool/webSocket.js

101 lines
2.3 KiB
JavaScript
Raw Normal View History

import {
setCookie,
getCookie,
WriteCookie,
clonAllCookie,
} from "@/tool/cookie";
2024-08-19 10:36:46 +08:00
import MyEvent from "@/tool/myEvents";
2024-08-13 09:36:13 +08:00
class MyWs {
constructor() {
this.ws = null;
// this.ws = new WebSocket();
let http = import.meta.env.VITE_APP_BASE_URL.replace(/^https?:\/\//, "");
this.messageUrl = http + "/notification";
this.wsUrl = "";
this.reconnectionTime = null;
this.times = 0;
this.sendPINGTime = null;
}
linkWs(url) {
if (!JSON.parse(getCookie("userInfo"))) return;
if (this.ws && this.ws.readyState == 1) return;
if (!this.wsUrl)
this.wsUrl = url + `/${JSON.parse(getCookie("userInfo")).userId}`;
this.ws = new WebSocket(this.wsUrl);
this.ws.onmessage = (e) => {
try {
let rv = JSON.parse(e.data);
if (rv == "PONG") return;
this.times = 0;
MyWs.receiveText(rv);
} catch (error) {
console.error("websocket", error);
}
};
clearInterval(this.sendPINGTime);
this.sendPINGTime = setInterval(() => {
this.send({ text: "PING" });
// },1000)
}, 1000 * 60 * 2);
this.ws.onclose = (e) => {
this.reconnection();
};
this.ws.onerror = (e) => {
this.reconnection();
};
}
reconnection() {
this.times++;
clearTimeout(this.reconnectionTime);
if (this.times >= 10) return;
clearInterval(this.sendPINGTime);
this.reconnectionTime = setTimeout(() => {
this.linkWs(this.wsUrl);
}, 1000);
}
static receiveText(data, call) {
MyEvent.emit("getMessage", data);
}
sendMessage(data) {
if (this.ws && this.ws.readyState == 1) {
let obj = {
cmd: 1,
data: {
name: "123",
},
};
this.send(obj);
obj = {
cmd: 4,
data: {
msg: data,
},
};
this.send(obj);
// obj = {
// cmd: 6,
// data: {
// msg: data,
// }
// }
// this.send(obj,this.ws)
}
}
send(obj) {
if (this.ws.readyState == 1) {
this.ws.send(JSON.stringify(obj));
} else {
clearTimeout(this.sendPINGTime);
this.reconnection();
}
}
close() {
if (this.ws && this.ws.readyState == 1) {
console.log("客户端 连接已关闭");
this.ws.close();
}
}
2024-08-13 09:36:13 +08:00
}
2024-08-19 10:36:46 +08:00
export default new MyWs();