Js前端:發送普通請求
fetch(...)
.then(()=>{})
.catch(()=>{})
Java后端:接收請求后調用請求處理函數,函數返回一個emiiter對象
public SseEmitter handleRequest(...) {// 創建一個 SseEmitter 對象,用于發送 SSE 事件SseEmitter emitter = new SseEmitter();...return emiiter; // 將 SseEmitter 對象返回給前端,以便前端可以訂閱 SSE 事件 (即:與前端建立 SSE 連接)
}
Js前端:創建一個 EventSource
對象,指定一個 GET 請求的 URL 來接收 SSE 事件
// 構建請求URL
const url = `/api/test`;// 創建一個新的 EventSource 對象,用于接受 SSE 事件
const eventSource = new EventSource(url);
Js前端:通過 EventSource
對象監聽 onmessage
事件
// 當接收到新的 SSE 事件時,觸發 onmessage 事件處理程序,然后在里面可以解析接收到的 JSON 數據// 監聽 SSE 消息eventSource.onmessage = function (event) {try {// 解析 JSON 格式的消息const data = JSON.parse(event.data);// 根據數據處理邏輯...}} catch (e) {console.log(e);}};
Js前端:通過 EventSource
對象監聽 onerror
事件
// 當發生錯誤時(例如網絡問題或服務器關閉連接),觸發 onerror 事件處理程序// 監聽 SSE 錯誤事件eventSource.onerror = function (error) {console.log(error);eventSource.close(); // 關閉 EventSource 連接};
Java后端:發送SSE事件,將數據推送到前端(可以發送后再發送,發了再發,不用關閉連接)
// 發送 SSE 事件,將獲取結果發送給前端
const message = "Hello World"
emitter.send(SseEmitter.event().data(message));
Java后端:如果不需要發送了,就關閉連接
// 調用下面方法,會發送一個特殊的 end-of-stream 字節序列通知客戶端連接已關閉
emitter.complete()
Java后端:如果在處理過程中發生異常,后端可以調用 emitter.completeWithError()
方法,這會發送一個錯誤事件給前端,并關閉連接
emitter.completeWithError(new Exception('出錯了'))
Js前端:瀏覽器在接收到 emitter.complete()
發送的特殊字節序列后,會自動將 EventSource
的 readyState
設置為 CLOSED
(值為 2),并關閉連接。
Js前端:當 EventSource
對象檢測到錯誤時(例如網絡問題、服務器關閉連接等),會觸發 onerror
事件,我們可以在里面輸入日志并關閉連接。通過這種方式,讓前端可以有效地管理和維護 SSE 連接,確保在各種情況下都能正確處理錯誤并關閉連接。
// 監聽 SSE 錯誤事件eventSource.onerror = function (error) {console.log(error);eventSource.close(); // 關閉 EventSource 連接};