文章目錄
- HTTP 非流式請求 vs 流式請求
- 一、核心區別
- 服務端代碼示例(Node.js/Express)
- 非流式請求處理
- 流式請求處理
- 客戶端請求示例
- 非流式請求(瀏覽器fetch)
- 流式請求處理(瀏覽器fetch)
- Python客戶端示例(Requests庫)
- 非流式請求
- 流式請求處理
- 關鍵特性對比
- 注意事項
HTTP 非流式請求 vs 流式請求
一、核心區別
-
非流式請求(傳統HTTP請求):
- 客戶端發送完整請求 → 服務端處理 → 返回完整響應
- 數據一次性完整傳輸
- 連接立即關閉
- 適用于普通API接口
-
流式請求(Streaming Request):
- 建立持久連接通道
- 服務端可持續分塊發送數據
- 客戶端可實時處理數據
- 適用于實時聊天、大文件傳輸、日志流等場景
服務端代碼示例(Node.js/Express)
非流式請求處理
app.get('/api/normal', (req, res) => {// 一次性生成完整數據const data = Array.from({length: 5}, (_, i) => `數據塊 ${i + 1}`);res.json({ status: 'complete',data: data});
});
流式請求處理
app.get('/api/stream', (req, res) => {// 設置流式響應頭res.setHeader('Content-Type', 'text/plain; charset=utf-8');res.setHeader('Transfer-Encoding', 'chunked');// 模擬持續發送數據let count = 0;const interval = setInterval(() => {if (count++ < 5) {res.write(`數據塊 ${count}\n`);} else {clearInterval(interval);res.end(); // 結束流}}, 1000);
});
客戶端請求示例
非流式請求(瀏覽器fetch)
fetch('/api/normal').then(response => response.json()).then(data => {console.log('完整數據:', data);});
流式請求處理(瀏覽器fetch)
fetch('/api/stream').then(async response => {const reader = response.body.getReader();const decoder = new TextDecoder();while(true) {const { done, value } = await reader.read();if(done) break;console.log('收到數據塊:', decoder.decode(value));}});
Python客戶端示例(Requests庫)
非流式請求
import requestsresponse = requests.get('http://localhost:3000/api/normal')
print("完整響應:", response.json())
流式請求處理
import requestswith requests.get('http://localhost:3000/api/stream', stream=True) as r:for chunk in r.iter_content(chunk_size=None):if chunk:print("實時數據:", chunk.decode('utf-8'))
關鍵特性對比
特性 | 非流式請求 | 流式請求 |
---|---|---|
響應方式 | 一次性完整返回 | 持續分塊返回 |
內存占用 | 需要完整加載數據 | 按需處理數據塊 |
延遲 | 等待完整數據處理 | 首字節到達即可處理 |
適用場景 | 常規API請求 | 實時數據/大文件傳輸 |
連接持續時間 | 立即關閉 | 保持長連接 |
客戶端處理復雜度 | 簡單 | 需要特殊處理邏輯 |
注意事項
- 流式請求需要設置正確的響應頭(
Transfer-Encoding: chunked
) - 客戶端需要處理連接中斷和重連邏輯
- 服務端要合理控制并發連接數
- 瀏覽器端需注意跨域問題(CORS配置)
- 流式傳輸更適合使用WebSocket/SSE等專業協議的場景需要考慮技術選型