fix: 修复同一帐号多人同时使用时无法自动刷新的问题

This commit is contained in:
jmal 2024-03-20 15:15:02 +08:00
parent 41f984ba1f
commit 48fca3ef85

View File

@ -1,16 +1,23 @@
import Bus from "@/assets/js/bus"; import Bus from "@/assets/js/bus";
import store from "@/store"; import store from "@/store";
import {generateUUID} from "ant-design-vue/lib/vc-select/util";
let eventSource = null; let eventSource = null;
let timer = null; let timer = null;
let lastHeartbeat = new Date().getTime();
export function connectToSSE(username) { export function connectToSSE(username) {
if (typeof (EventSource) !== 'undefined') { if (typeof (EventSource) !== 'undefined') {
const url = `/api/events?username=${username}`; const url = `/api/events?username=${username}&uuid=${generateUUID()}`;
eventSource = new EventSource(url); eventSource = new EventSource(url);
eventSource.addEventListener('message', function (event) { eventSource.addEventListener('message', function (event) {
const msg = JSON.parse( event.data); if (event.data === 'h') {
onMessage(msg) // 心跳包, 超过5s没有收到心跳包, 则关闭连接
lastHeartbeat = new Date().getTime()
} else {
const msg = JSON.parse( event.data);
onMessage(msg)
}
}); });
eventSource.addEventListener('error', function (event) { eventSource.addEventListener('error', function (event) {
eventSource.close() eventSource.close()
@ -19,12 +26,18 @@ export function connectToSSE(username) {
if (timer) { if (timer) {
clearInterval(timer); clearInterval(timer);
} }
// 1s检测一次连接状态 // 3s检测一次连接状态
timer = setInterval(() => { timer = setInterval(() => {
if (eventSource.readyState === 1) {
// 心跳包, 超过5s没有收到心跳包, 则关闭连接
if (new Date().getTime() - lastHeartbeat > 5000) {
eventSource.close()
}
}
if (eventSource.readyState === 2) { if (eventSource.readyState === 2) {
connectToSSE(username); connectToSSE(username);
} }
}, 1000); }, 3000);
} else { } else {
console.error('EventSource is not supported by the browser'); console.error('EventSource is not supported by the browser');