$f = fsockopen("www....",80,$x,$y);
fwrite("GET request HTTP/1.1\r\nConnection: keep-alive\r\n\r\n");
while($s = fread($f,1024)){
...
}
The above stalls because of the Connection: keep-alive
, and works with Connection: close
.
How do you do it without stalling?
The following code works without any problem for me:
The funny thing is that without keep-alive this example stalls for me. Can you add an example that can be just copy&pasted and shows your error?
It depends on the response, if the
transfer-encoding
of the response ischunked
, then you read until you encounter the "last chunk" (\r\n0\r\n
).If the
content-encoding
isgzip
, then you look at thecontent-length
response header and read that much data and then inflate it. If thetransfer-encoding
is also set to chunked, then you must dechunk the decoded response.The easiest thing is to build a simple state machine to read the response from the socket while there is still data left for the response.
When reading chunked data, you should read the first chunk length (and any chunked extension) and then read as much data as the chunk size, and do so until the last chunk.
Put another way:
\r\n\r\n
)transfer-encoding
is chunked, read and dechunk the data piece by piece.content-length
header is set, you can read that much data from the socketcontent-encoding
is gzip, decompress the read dataOnce you have performed the above steps, you should have read the entire response and you can now send another HTTP request on the same socket and repeat the process.
On the other hand, unless you have the absolute need for a keep-alive connection, just set
Connection: close
in the request and you can safely readwhile (!feof($f))
.I don't have any PHP code for reading and parsing HTTP responses at the moment (I just use cURL) but if you'd like to see actual code, let me know and I can work something up. I could also refer you to some C# code I've made that does all of the above.
EDIT: Here is working code that uses
fsockopen
to issue an HTTP request and demonstrate reading keep-alive connections with the possibility of chunked encoding and gzip compression. Tested, but not tortured - use at your own risk!!!