优化WebSocket组件

This commit is contained in:
zjl 2024-12-18 15:35:30 +08:00
parent b63b3267ef
commit 129cdcfd0c

View File

@ -7,12 +7,18 @@
const emit = defineEmits(['rollback']);
/**
* 定义接收的参数
*/
const props = defineProps({
uri: {
type: String,
},
});
/**
* 定义Socket状态
*/
const state = reactive({
webSocket: ref(), // webSocket
lockReconnect: false, //
@ -27,6 +33,9 @@ const state = reactive({
},
});
/**
* 获取Token令牌
*/
const token = computed(() => {
return useUserStore().getToken;
});
@ -35,6 +44,9 @@ const tenant = computed(() => {
return Session.getTenant();
});
/**
* 钩子函数
*/
onMounted(() => {
initWebSocket();
});
@ -44,6 +56,9 @@ onUnmounted(() => {
clearTimeoutObj(state.heartbeat);
});
/**
* 初始化WebSocket对象
*/
const initWebSocket = () => {
// ws
let host = window.location.host;
@ -61,11 +76,17 @@ const initWebSocket = () => {
state.webSocket.onclose = onClose;
};
/**
* 重连机制
*/
const reconnect = () => {
if (!token) {
if (!token.value) {
return;
}
if (state.lockReconnect || (state.maxReconnect !== -1 && state.reconnectTime > state.maxReconnect)) {
if (
state.lockReconnect ||
(state.maxReconnect !== -1 && state.reconnectTime > state.maxReconnect)
) {
return;
}
state.lockReconnect = true;
@ -76,6 +97,7 @@ const reconnect = () => {
state.lockReconnect = false;
}, 5000);
};
/**
* 清空定时器
*/
@ -83,6 +105,7 @@ const clearTimeoutObj = (heartbeat: any) => {
heartbeat.pingTimeoutObj && clearTimeout(heartbeat.pingTimeoutObj);
heartbeat.pongTimeoutObj && clearTimeout(heartbeat.pongTimeoutObj);
};
/**
* 开启心跳
*/
@ -116,6 +139,7 @@ const onOpen = () => {
startHeartbeat();
state.reconnectTime = 0;
};
/**
* 连接失败事件
* @param e
@ -133,9 +157,10 @@ const onClose = () => {
//
reconnect();
};
/**
* 接收服务器推送的信息
* @param msgEvent
* @param msgEvent 消息事件
*/
const onMessage = (msgEvent: any) => {
//