Home >Backend Development >PHP Tutorial >Determining the End of HTTP Request in Keep-Alive Mode_PHP Tutorial
When using the short connection method, each HTTP request corresponds to a TCP connection. After the request is completed, the connection is immediately disconnected and the server returns EOF. Therefore, the end of a request can be determined based on EOF. The following code (PHP) is very common:
Copy to ClipboardQuoted content: [www.bkjia.com] // $fp is the handle generated by fsockopen()(Note: The short connection mode is marked with "Connection: close" in the header, and the long connection is marked with "Connection: keep-alive". Currently, HTTP/1.0 uses short connections by default, and HTTP/1.1 uses long connections by default. )
In the HTTP mode of long connection (also called persistent connection), the server does not disconnect the connection after sending the data, but keeps it for the next HTTP request, so the benefits of long connection are obvious, Passed Share a TCP connection to save the overhead of establishing/disconnecting connections during future requests . EOF will not be sent until the TCP connection ends (timeout or error), so we cannot use the above method to judge the end of an HTTP request. This is also a problem encountered when using long connections. There are currently two main methods of judgment:
(1) According to the Content-Length field in the header. This field indicates the length of the text. We can judge the end based on receiving characters of the specified length.
(2) When there is no Content-Length, based on Transfer-Encoding. Sometimes the server cannot determine the size of the text because the text may be dynamically generated, so Content-Length will not be provided. Instead, chunk encoding is used to send the text piece by piece. Each chunk block consists of two parts: a header and a body. A hexadecimal number in the header specifies the length of the body. Finally, a chunk block with a length of 0 indicates the end of the entire HTTP body.
Below I use PHP to implement the judgment method when there is Content-Length:
1. Get Content-Length value
Copy to ClipboardQuoted content: [www.bkjia.com] $length = 0;2. Get the text
Copy to ClipboardQuoted content: [www.bkjia.com] $sum = 0;