fix: To resolve SSE (Server-Sent Events) issue "Waiting for connections to close."

This commit is contained in:
swpa 2026-05-18 15:40:19 +08:00
parent 17ff31dcf7
commit 78b7493bd4
2 changed files with 18 additions and 4 deletions

View File

@ -41,14 +41,20 @@ async def sse_stream(request: Request):
async def event_generator():
try:
while True:
try:
message = await asyncio.wait_for(client_queue.get(), timeout=2.0)
yield message
except asyncio.TimeoutError:
# 🌟 每次迴圈先檢查前端是否已經斷線 (按了 F5)
if await request.is_disconnected():
break
# 🌟 關鍵修復 2每 2 秒發送一個空註解,防止瀏覽器因閒置而自動斷線
try:
# 縮短 timeout 為 1 秒,讓檢查更靈敏
message = await asyncio.wait_for(client_queue.get(), timeout=1.0)
yield message
except asyncio.TimeoutError:
yield ": keepalive\n\n"
except asyncio.CancelledError:
# 🌟 關鍵修復:當 Uvicorn 觸發 reload 關閉伺服器時,會拋出此例外
# 我們捕捉它並默默退出,不讓伺服器卡住
pass
finally:
active_clients.discard(client_queue)

View File

@ -93,6 +93,14 @@ function initGlobalSSE() {
};
}
// 🌟 關鍵修復:當使用者按 F5 重整或關閉網頁時,主動切斷 SSE 連線
window.addEventListener('beforeunload', () => {
if (globalSSE) {
globalSSE.close();
globalSSE = null;
}
});
// 頁面載入與縮放初始化
window.onload = () => {
initTerminal();