Are HTTP keep-alive connections possible without content-length headers?

我是研究僧i 提交于 2019-12-22 08:54:59

问题


I understand that in HTTP 1.0, the content of a response is terminated by closing the connection.

In HTTP 1.1, keep-alive connections were introduced, enabling multiple requests and responses in a single TCP connection.

When multiple messages are sent over the same connection, there needs to be a mechanism that defines where one message ends and the next message starts.

By testing, I found out that this works when I set the content-length header in a response. By knowing the content length, the client knows when the content is fully received and can parse the next response.

My question is:

Is it possible to send multiple responses in a keep-alive connection without setting the content-length header?

If yes, how?

For clarification: I am thinking about scenarios where the length of the response is not known when starting to send it to the client and I would like to know if closing the connection is the only way to implement that.


回答1:


The Transfer-Encoding header is what I was looking for.

By setting the transfer-encoding to chunked, it is possible to omit the Content-Length header.

In the chunked transfer encoding, a message can be sent in multiple chunks for which the length is known. To terminate a message, a chunk with length zero is sent.

This makes it possible to have a keep-alive connection and still send messages where the length is unknown when starting to send them.



来源:https://stackoverflow.com/questions/49256096/are-http-keep-alive-connections-possible-without-content-length-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!