3
votes

Could someone tell me about that Content-Length or Transfer-Encoding: "Chunked" is a must for Http request ? I'm using c++ to write a http sever.

The http respond can use close socket to know the length of message body. But how about request ?

I have checked RFC2616 about http 1.1, but I'm not clear enough about that.

My question is if a http request sent out without "Content-Length" or "Chunked Transfer-Encoding",how could I use "WSARecv" to know the length of message body, for the case I use WSARecv and get all the headers and net stream ends with "\r\n\r\n" coincidentally, I fail to get the length of message body. If I deliver a WSARecv again,it may wait forever because there is no more data. If I do not deliver "WSARecv" again, i may not get the message body after if there has.

Or maybe the "Content-Length" and "chunked transfer-encoding" is a must for http request ? client should set one of them to tell sever the length of message ?

2
There is nothing 'coincidental' about the blank line at the end of the headers. It is specified in the HTTP RFCs. - user207421
Have you considered using a library such as libmicrohttp to do most of the grunt work for you? - Martin Bonner supports Monica

2 Answers

3
votes

If you don't specify a Transfer-Encoding or Content-Length then the request (or response) is implicitly a variable length request/response and the only way to signal the end of the body is to shutdown the connection (and conversely detect the shutdown/eof in the receiver).

This means that this kind of request/response is also implicitly Connection: close

If you're implementing HTTP1.1 then you must support all three transfer methods.

When I wrote my HTTP server I abstracted the concept of a "request stream" from the concept of a "connection stream". The "request stream" is polymorphic and supports the concept of reading to "EOF". There's no reason you couldn't also have a method on there to "read_chunk". In the case of a non-chunked request, this could simply read until EOF.

This allowed me to implement simultaneous execution of multiple requests on the same connection (but there is some jiggery-pokery to ensure that the responses go back in the correct order!)