当我发送HTTP请求时,我想在我需要一个接一个地发送少量请求时使用Connection: Keep-Alive
。如何检查套接字是否包含数据?
我的预期代码:
$soc = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$t = socket_connect($soc, gethostbyname('www.example.com'), 80);
if (!$t) {
die(socket_strerror(socket_last_error($soc)));
}
$request = "GET /index.php HTTP/1.1\r\n";
$request .= "Host: www.example.com\r\n";
$request .= "Connection: Keep-Alive\r\n";
$request .= "\r\n";
socket_write($soc, $request);
$buffer = '';
$html = '';
while (socket_data_available($soc)/* THIS FUNCTION DOES NOT EXIST*/) {
socket_recv($soc, $buffer, 2048, MSG_WAITALL);
$html .= $buffer;
}
答案 0 :(得分:0)
在我看来,您不想检查套接字是否包含数据(无论这意味着什么),而是要读取HTTP响应然后继续。这可以通过替换上面的循环来实现:
while ($buffer = socket_read($soc, 2048, PHP_NORMAL_READ))
{
$html .= $buffer;
if ($buffer == "\r") break;
if ($buffer == "\n") continue;
list($key, $val) = explode(' ', $buffer, 2);
if ($key == "Content-Length:") $length = $val;
}
$html .= socket_read($soc, 1+$length);