Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 514
Lukas Boersma Avatar asked Mar 13 '18 12:03

Lukas Boersma


People also ask

Is the content length header necessary in HTTP?

The Content-Length is optional in an HTTP request. For a GET or DELETE the length must be zero. For POST, if Content-Length is specified and it does not match the length of the message-line, the message is either truncated, or padded with nulls to the specified length.

How do I keep my HTTP connection alive?

The default HTTP connection is usually closed after each request has been completed, meaning that the server closes the TCP connection after delivering the response. In order to keep the connection open for multiple requests, the keep-alive connection header can be used.

Why do we need content length header?

The Content-Length header indicates the size of the message body, in bytes, sent to the recipient.

Does HTTP have Keep-Alive?

The HTTP keep-alive header maintains a connection between a client and your server, reducing the time needed to serve files. A persistent connection also reduces the number of TCP and SSL/TLS connection requests, leading to a drop in round trip time (RTT).


1 Answers

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.

like image 103
Lukas Boersma Avatar answered Oct 14 '22 08:10

Lukas Boersma