From 48fca3ef858f7f857ae67684e5e3aca95273b47a Mon Sep 17 00:00:00 2001 From: jmal Date: Wed, 20 Mar 2024 15:15:02 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=90=8C=E4=B8=80?= =?UTF-8?q?=E5=B8=90=E5=8F=B7=E5=A4=9A=E4=BA=BA=E5=90=8C=E6=97=B6=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E6=97=B6=E6=97=A0=E6=B3=95=E8=87=AA=E5=8A=A8=E5=88=B7?= =?UTF-8?q?=E6=96=B0=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/sse/SSEClient.js | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/sse/SSEClient.js b/src/sse/SSEClient.js index 8a2a9dc..a0b0e53 100644 --- a/src/sse/SSEClient.js +++ b/src/sse/SSEClient.js @@ -1,16 +1,23 @@ import Bus from "@/assets/js/bus"; import store from "@/store"; +import {generateUUID} from "ant-design-vue/lib/vc-select/util"; let eventSource = null; let timer = null; +let lastHeartbeat = new Date().getTime(); export function connectToSSE(username) { if (typeof (EventSource) !== 'undefined') { - const url = `/api/events?username=${username}`; + const url = `/api/events?username=${username}&uuid=${generateUUID()}`; eventSource = new EventSource(url); eventSource.addEventListener('message', function (event) { - const msg = JSON.parse( event.data); - onMessage(msg) + if (event.data === 'h') { + // 心跳包, 超过5s没有收到心跳包, 则关闭连接 + lastHeartbeat = new Date().getTime() + } else { + const msg = JSON.parse( event.data); + onMessage(msg) + } }); eventSource.addEventListener('error', function (event) { eventSource.close() @@ -19,12 +26,18 @@ export function connectToSSE(username) { if (timer) { clearInterval(timer); } - // 1s检测一次连接状态 + // 3s检测一次连接状态 timer = setInterval(() => { + if (eventSource.readyState === 1) { + // 心跳包, 超过5s没有收到心跳包, 则关闭连接 + if (new Date().getTime() - lastHeartbeat > 5000) { + eventSource.close() + } + } if (eventSource.readyState === 2) { connectToSSE(username); } - }, 1000); + }, 3000); } else { console.error('EventSource is not supported by the browser');