Keep Alive – mode

We all know that HTTP is based on TCP, and every HTTP request requires a three-step handshake. If a page has multiple requests for a domain name, frequent connections are established and disconnected. So in HTTP 1.0, Connection: keep-alive was used to establish long connections, which is what we call keep-alive mode. The following is a comparison of normal and long connection mode requests:

Connection: close is used by default in HTTP/1.0. Connection: keep-alive is used by default in HTTP/1.1.

The comparison shows that the keep-alive mode is more efficient because it avoids the overhead of connection establishment and release. But if a connection is never broken, how can multiple requests be distinguished? That is, how does the browser know that the current request is completed? To solve this problem, HTTP adds a content-Length field to the header.

Content-Length

Content-length Specifies the Length of the entity Content. The browser uses this field to determine whether all of the data currently requested has been received. So when the browser requests a static resource, and the server knows exactly how long the Content will be returned, you can set Content-Length to control the end of the request. But when the server does not know the Length of the requested result, such as a dynamic page or data, content-Length cannot solve this problem, and transfer-Encoding is needed.

Transfer-Encoding

Transfer-encoding refers to the Transfer Encoding, and there is a similar field called content-encoding. The difference between the two is that content-encoding is used to compress entity Content, such as content-encoding: gzip; Transfer-encoding changes the format of the message. For example, in the above problem, when the server does not know the length of the entity content, transfer-encoding: chunked can be used to tell the browser that the current Encoding is transferring the data in chunks. Of course, you can also specify transfer-encoding: gzip, chunked to indicate that the entity content is not only gzip-compressed, but also chunked. Finally, when the browser receives a chunked of length 0, it knows that the current request has been received in full.