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