v4if / blog

:octocat: 用issues写博客,记录点滴
35 stars 7 forks source link

HTTP协议数据的结束 #39

Open v4if opened 6 years ago

v4if commented 6 years ago

Assuming you want your client to work with other servers, and server to work with other clients, your server can't expect to be treated nicely. There are two ways to tell when the body has ended. Neither of them require knowledge of the body's content type as you suggest (e.g., don't bother looking for -- that goes far outside the HTTP protocol). 1、If the client sends a message with Transfer-Encoding: Chunked, you will need to parse the somewhat complicated chunked transfer encoding syntax. You don't really have much choice in the matter -- if the client is sending in this format, you have to receive it. When the client is using this approach, you can detect the end of the body by a chunk with a length of 0. 2、If the client instead sends a Content-Length, you must use that.

HTTP由请求头、请求行、请求主体构成,没有Content-Length 只有两种情况,否则就不是一个标准的http server 1、传输完毕就关闭connection 2、HTTP 1.1 没有Content-Length,但是 Transfer-Encoding: chunked,最后一个chunk的length==0

总体流程大致是: 1、先把header直到\r\n\r\n整个地收下来; 2、如果Connection: Keep-Alive: 1)if T-E: chunked, 就读, 直到流里有\r\n0\r\n\r\n

HTTP/1.1 200 OK
Content-Type: text/plain
Transfer-Encoding: chunked

25
This is the data in the first chunk

1C
and this is the second one

3
con

8
sequence

0

2)else if Content-Length存在, 就从头到末尾开始计算C-L个字节. 3、else 就这么一直读等服务器断开连接就好.