HTTP 响应的分块传输

栏目: 后端 · 前端 · 发布时间: 6年前

内容简介:其可选值有:也可以同时指定多个值,用逗号分隔,像这样:

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(`<p> chunk ${index}</p>`);
    }
  }, index * 1000);
}

function handlerRequest(_request, response) {
  response.setHeader("Content-Type", "text/html; charset=UTF-8");
  response.setHeader("Transfer-Encoding", "chunked");
  response.write(`<!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="utf-8">
  <title>HTTP 分块传输示例</title>
  </head>
  <body>
  <h1>HTTP 分块传输示例</h1>
  `);

  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");

HTTP 响应的分块传输

Transfer-Encoding:chunked 分块传输示例

总结

HTTP/2 中已经不支持 chunked 这一格式了,因为其本身提供了更加高级的流机制来实现类似功能。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

RESTful Web Services Cookbook

RESTful Web Services Cookbook

Subbu Allamaraju / Yahoo Press / 2010-3-11 / USD 39.99

While the REST design philosophy has captured the imagination of web and enterprise developers alike, using this approach to develop real web services is no picnic. This cookbook includes more than 10......一起来看看 《RESTful Web Services Cookbook》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

html转js在线工具
html转js在线工具

html转js在线工具