Files
sgxt_web/src/utils/webSocket.js

76 lines
1.6 KiB
JavaScript
Raw Normal View History

2025-04-12 14:54:02 +08:00
const url = "ws://80.155.0.82:8006/mosty-api/mosty-websocket/socket/"; //线上
import {
getItem
} from "@/utils/storage";
import {
getUserInfoToId
} from "@/api/user-manage";
class WebSoketClass {
constructor(props) {}
ws = null;
static getInstance() {
if (!this.ws) this.ws = new WebSoketClass();
return this.ws;
}
//关闭连接
static close() {
this.ws.ws.close();
}
// 创建连接
connect(fun) {
let uuid = this.getUUid()
let id = getItem("USERID");
getUserInfoToId(id).then((res) => {
let sfzh = res.idEntityCard
this.ws = new WebSocket(url + sfzh + '/' + uuid);
this.ws.onopen = (e) => { fun(true);};
});
}
// 心跳机制
heartCheck() {
const _that = this;
this.state = setInterval(() => {
if (this.ws.readyState === 1) {
this.ws.send("/heart");
} else {
this.closeHandle(); //重新连接
}
}, 6e3);
}
// 获取uuid
getUUid() {
var s = [];
var hexDigits = "0123456789abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 32; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4";
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
s[8] = s[13] = s[18] = s[23];
let uuid = s.join("");
return uuid
}
closeHandle() {
if (this.state) {
clearInterval(this.state);
this.connect();
} else {
}
}
// 接收发送消息
getMessage() {
this.ws.onmessage = (e) => {
if (e.data) {
let newsDate = JSON.parse(e.data);
this.newVal = newsDate;
//接收的数据
}
};
}
}
export default WebSoketClass;