




選擇SSE還是WebSocket,取決于具體的業(yè)務需求。如果只需要服務器向客戶端推送數(shù)據(jù),且對通信性能要求不高,SSE是一個簡單高效的選擇;而如果需要雙向通信或?qū)π阅芤筝^高,WebSocket則更為適合。
三、標準的EventSource API
在瀏覽器中,SSE通過EventSource對象實現(xiàn)。以下是EventSource API的主要特性和用法:
1. 創(chuàng)建EventSource對象
使用EventSource對象時,需要指定服務器的URL:
const eventSource = new EventSource(https://example.com/sse);
2. 事件監(jiān)聽
EventSource支持三種事件類型:
message:處理默認事件。
open:連接成功時觸發(fā)。
error:連接出錯或斷開時觸發(fā)。
示例代碼:
eventSource.onopen = function(event) {
console.log('Connection opened:', event);
};
eventSource.onmessage = function(event) {
console.log('Message received:', event.data);
};
eventSource.onerror = function(event) {
console.error('Error occurred:', event);
};
3. 自定義事件類型
服務器可以發(fā)送自定義事件類型,客戶端可以通過addEventListener監(jiān)聽:
eventSource.addEventListener('custom-event', function(event) {
console.log('Custom event received:', event.data);
});
4. 關(guān)閉連接
可以通過調(diào)用close()方法手動關(guān)閉連接:
eventSource.close();
console.log('Connection closed');
5. 服務器發(fā)送數(shù)據(jù)格式
服務器需要按照以下格式發(fā)送數(shù)據(jù):
data: Hello, World!
event: custom-event
id: 12345
retry: 3000
data:事件數(shù)據(jù)。
event:事件類型(可選)。
id:事件ID,用于斷線重連時恢復狀態(tài)(可選)。
retry:指定重連間隔時間(以毫秒為單位,可選)。
四、@microsoft/fetch-event-source 介紹
@microsoft/fetch-event-source是微軟開發(fā)的一個輕量級庫,用于在Node.js和瀏覽器環(huán)境中實現(xiàn)SSE(Server-Sent Events)。與原生的EventSource相比,它提供了更多的靈活性和功能,例如支持自定義HTTP方法(如POST)、請求頭、認證、請求體等。
npm倉庫:https://www.npmjs.com/package/@microsoft/fetch-event-source。
1. 安裝
可以通過npm或yarn安裝:
npm install @microsoft/fetch-event-source
2. 使用示例
以下是一個簡單的使用示例:
import { fetchEventSource } from '@microsoft/fetch-event-source';
fetchEventSource(https://example.com/sse, {
method: POST,
headers: {
Content-Type: application/json,
Authorization: Bearer YOUR_TOKEN,
},
body: JSON.stringify({ key: value }),
onopen(response) {
if (response.ok && response.headers.get('content-type') === 'text/event-stream') {
console.log('Connection established');
} else {
console.error('Connection failed');
}
},
onmessage(event) {
console.log('Message received:', event.data);
},
onclose() {
console.log('Connection closed by server');
},
onerror(err) {
console.error('Error occurred:', err);
},
});
3. 特性
(1)支持自定義HTTP方法(如POST)。
(2)支持請求頭和請求體。
(3)提供事件鉤子(如onopen、onmessage、onclose、onerror)。
(4)支持斷線重連。
五、@microsoft/fetch-event-source 原理解析
@microsoft/fetch-event-source的實現(xiàn)基于fetch API,通過流式處理實現(xiàn)了SSE的功能。以下是其核心實現(xiàn)原理的解析:
1. 核心邏輯
該庫的核心邏輯是使用fetch API發(fā)起HTTP請求,并通過ReadableStream解析服務器返回的事件流。
源碼片段(簡化版):
async function fetchEventSource(url, options) {
const response = await fetch(url, options);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop(); // 保留未完整的行
for (const line of lines) {
if (line.startsWith('data:')) {
const data = line.slice(5).trim();
options.onmessage({ data });
}
}
}
options.onclose();
}
2. POST傳參的實現(xiàn)
與原生EventSource不同,該庫允許通過POST方法發(fā)送參數(shù)。實現(xiàn)方式是將請求體傳遞給fetch API:
fetch(url, {
method: 'POST',
headers: options.headers,
body: options.body,
});
3. 自動重連
當連接斷開時,庫會自動嘗試重新連接:
setTimeout(() => {
fetchEventSource(url, options);
}, retryInterval);
4. 錯誤處理
通過try-catch捕獲錯誤,并調(diào)用onerror回調(diào):
try {
// 讀取流數(shù)據(jù)
} catch (err) {
options.onerror(err);
}
熱門文章
相關(guān)文章
極光官方微信公眾號
關(guān)注我們,即時獲取最新極光資訊
現(xiàn)在注冊,領取新人大禮包