xw_admin/src/utils/websocket.js
2024-09-04 19:32:50 +08:00

198 lines
4.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//@eslint-disable
import tool from '@/utils/tool';
import systemConfig from '@/config';
import api from '../api';
import router from "@/router";
import {ElNotification} from 'element-plus';
import {eventBus} from "./eventBus"
// import store from "../store";
let websocket = null;
let global_callback = function () {};
let timeoutObj = null;
let timeout = 28 * 1000; //30秒一次心跳
let serverTimeoutObj = 60; //心跳倒计时
let timeOutNum = 60; //断开 重连倒计时
let lockReconnect = false; //是否真正建立连接
const wsUri = systemConfig.WS_URL;
let showNot = null;
function networkDes() {
ElNotification.error({
title: '网络已断开',
message: '网络已断开,正在重连……'
})
}
function reConnect() {//重新连接
if (lockReconnect) {
return;
}
lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
timeOutNum && clearTimeout(timeOutNum);
timeOutNum = setTimeout(function () {
//新连接
createWebSocket(global_callback);
lockReconnect = false;
}, 5000);
}
function startHeartbeat() {
//清除时间
clearTimeout(timeoutObj);
clearTimeout(serverTimeoutObj);
start();
}
function start() {//开启心跳
timeoutObj && clearTimeout(timeoutObj);
serverTimeoutObj && clearTimeout(serverTimeoutObj);
timeoutObj = setTimeout(function () {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
if (websocket.readyState === 1) {//如果连接正常
const heart = {type: "heart"}
websocket.send(JSON.stringify(heart));
} else {//否则重连
reConnect();
}
serverTimeoutObj = setTimeout(function () {
//超时关闭
closeSock(false);
}, timeout);
}, timeout)
}
function createWebSocket(callback, token) {
if (websocket == null || typeof websocket !== WebSocket) {
initWebSocket(callback, token);
}
}
function initWebSocket(callback, token) {
global_callback = callback;
// 初始化websocket
let reToken = token === undefined ? tool.cookie.get('TOKEN') : token;
if(!reToken) return // 没有token 不执行ws创建
websocket = new WebSocket(wsUri + "?token=Bearer " + reToken);
websocket.onmessage = function (e) {
webSocketOnMessage(e);
};
websocket.onclose = function (e) {
webSocketClose(e);
};
websocket.onopen = function () {
websocketOpen();
};
// 连接发生错误的回调方法
websocket.onerror = function () {
networkDes()
reConnect()
};
}
// 实际调用的方法
function sendSock(agentData) {
if (websocket.readyState === websocket.OPEN) {
// 若是ws开启状态
webSocketSend(agentData);
} else if (websocket.readyState === websocket.CONNECTING) {
// 若是 正在开启状态则等待1s后重新调用
setTimeout(function () {
sendSock(agentData);
}, 1000);
} else {
// 若未开启 则等待1s后重新调用
setTimeout(function () {
sendSock(agentData);
}, 1000);
}
}
function closeSock(active) {
lockReconnect = active; // 主动断开时不重连
websocket.close();
}
// 数据接收
function webSocketOnMessage(msg) {
// 收到信息为Blob类型时
let result = null;
// debugger
// 二进制文件
if (msg.data instanceof Blob) {
const reader = new FileReader();
reader.readAsText(msg.data, "UTF-8");
reader.onload = () => {
result = JSON.parse(reader.result);
global_callback(result);
};
} else {
if(msg.type === "") return
result = JSON.parse(msg.data);
// if(result.type == 13){
// store.commit("SET_WS_Msg_NUM", result.data.todo_msg_count);
// }
if(global_callback){
global_callback(result);
}
}
if (result.data && (result.data.type == -1 || result.data.type == 0 || result.data.type == 9 || result.data.type == 13)) {
if(result.data.type == -1 || result.data.type == 0){
if(result.data && result.data.data && result.data.data.token){
let reToken = result.data.data.token.replace(/Bearer /g, "");
tool.cookie.set("TOKEN", reToken);
}
}else{
showNot = ElNotification.error({
title: '系统退出',
message: result.data.msg,
duration:0
});
handleError('系统退出', result.msg);
}
}
eventBus.$emit('sockBack',result);
if(result.data && result.data.type == 1){
if(showNot && showNot.close){
showNot.close();
}
}
startHeartbeat()
}
function handleError() {
api.system.user.logout.post().then();
router.replace({ path: "/login" }).then();
closeSock(true);
}
function getSock(callback) {
global_callback = callback;
}
// 数据发送
function webSocketSend(agentData) {
websocket.send(agentData);
}
// 关闭
function webSocketClose() {
reConnect()
}
function websocketOpen() {
start()
}
export {
sendSock,
createWebSocket,
closeSock,
getSock,
reConnect,
};