Transfer-Encoding
響應頭用於告訴客戶端服務器發送內容的編碼格式。
其可選值有:
chunked
:數據分塊發送。此時應缺省Content-Length
響應頭。compress
:使用 Lempel-Ziv-Welch 算法進行傳輸的格式,目前沒有瀏覽器在支持。deflate
:使用 deflate 壓縮算法 zlib 結構。gzip
:使用 Lempel-Ziv coding 編碼的壓縮格式。identity
:標識身份函數(e.g. no compression, nor modification)。
也可以同時指定多個值,用逗號分隔,像這樣:Transfer-Encoding: gzip, chunked
。
其中,chunked
就比較有意思了。它表示服務器下發到客戶端的內容不是一次性完成的,而是分成一小塊一小塊(trunk)下發,過程中客戶端與服務器的連接仍然維持不會斷開。
在 Web Socket 沒出來前,可利用這一機制實現長連接的效果。
示例
以 Node.js 為例的 Transfer-Encoding: gzip, chunked
示例:
var http = require("http");
function generateChunk(index, response) {
setTimeout(() => {
if (index === 5) {
response.write("end");
response.end("</body></html>");
} else {
response.write(</span><p> chunk <span class="pl-s1"><span class="pl-pse">${</span>index<span class="pl-pse">}</span></span></p><span class="pl-pds">
);
}
}, index * 1000);
}
function handlerRequest(_request, response) {
response.setHeader("Content-Type", "text/html; charset=UTF-8");
response.setHeader("Transfer-Encoding", "chunked");
response.write(</span><!DOCTYPE html></span> <span class="pl-s"> <html lang="en"></span> <span class="pl-s"> <head></span> <span class="pl-s"> <meta charset="utf-8"></span> <span class="pl-s"> <title>HTTP 分塊傳輸示例</title></span> <span class="pl-s"> </head></span> <span class="pl-s"> <body></span> <span class="pl-s"> <h1>HTTP 分塊傳輸示例</h1></span> <span class="pl-s"> <span class="pl-pds">
);
let index = 0;
while (index <= 5) {
generateChunk(index, response);
index++;
}
}
const server = http.createServer(handlerRequest);
server.listen(3000);
console.log("server started at http://localhost:3000");
Transfer-Encoding:chunked 分塊傳輸示例
總結
HTTP/2 中已經不支持 chunked
這一格式了,因為其本身提供了更加高級的流機制來實現類似功能。