So depending on the EOF to determine the end of a request, the following code (PHP) is common:
Copy Code code as follows:
$FP is the handle produced by Fsockopen ()
while (!feof ($fp)) {
Echo fgets ($FP);
}
(Note: The short connection mode is marked with "Connection:close" in the head, and the long connection is marked with "connection:keep-alive".) Currently http/1.0 uses a short connection by default, and http/1.1 uses a long connection by default. )
The long connection (also known as persistent connection) mode of HTTP after sending data after the server is not disconnected, but to keep the next HTTP request to use, so the benefits of long connection is obvious, by sharing a TCP connection to save later requests to establish/disconnect the cost of the connection. EOF is not sent until the end of the TCP connection (timeout or error), so we cannot use the above method to determine the end of an HTTP request. This is also a problem that can be encountered when using long connections. There are two main ways of judging at present:
(1) According to the Content-length field in the header. This field indicates the length of the body, and we can determine the end of the character by receiving the specified length.
(2) In the absence of content-length, according to Transfer-encoding. Sometimes the server is unable to determine the body size, because the body may be dynamically generated, so it will not provide content-length, but use the chunk code to send a piece of text. Each chunk block consists of the head and the body two parts, the head in a 16 digits to specify the length of the body, and finally by a chunk length of 0 block to represent the end of the entire HTTP body.
Here I use PHP to achieve a content-length when the way to judge:
1. Get content-length value
Copy Code code as follows:
$length = 0;
$line = ';
while ($line!== "\ r \ n") {
$line = fgets ($FP);
if (substr ($line, 0,) = = ' Content-length: ') {
$length = Intval (substr ($line, 16));
}
}
2. Get the text
Copy Code code as follows:
$sum = 0;
while ($sum < $length) {
$line = fgets ($FP);
$sum + + strlen ($line);
Echo $line;
}