zoukankan      html  css  js  c++  java
  • HTTP 响应的分块传输

    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>&lt;p&gt; chunk <span class="pl-s1"><span class="pl-pse">${</span>index<span class="pl-pse">}</span></span>&lt;/p&gt;<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>&lt;!DOCTYPE html&gt;</span> <span class="pl-s"> &lt;html lang="en"&gt;</span> <span class="pl-s"> &lt;head&gt;</span> <span class="pl-s"> &lt;meta charset="utf-8"&gt;</span> <span class="pl-s"> &lt;title&gt;HTTP 分块传输示例&lt;/title&gt;</span> <span class="pl-s"> &lt;/head&gt;</span> <span class="pl-s"> &lt;body&gt;</span> <span class="pl-s"> &lt;h1&gt;HTTP 分块传输示例&lt;/h1&gt;</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 分块传输示例

    Transfer-Encoding:chunked 分块传输示例

    总结

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

    相关资源

  • 相关阅读:
    webstorm打开项目找不到git
    Redis 下载与安装(Windows版)
    element-UI el-table样式(去边框和滚动条样式)
    MVVM
    HTTP
    TCP/IP
    vue双向绑定
    Vue组件化原理
    JavaScript
    css中可继承与不可继承属性
  • 原文地址:https://www.cnblogs.com/Wayou/p/http_transfer_encoding_chunked.html
Copyright © 2011-2022 走看看