1

当我发送 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;
    }
4

1 回答 1

1

在我看来,您不想检查套接字是否包含数据(无论这意味着什么),而是要读取 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);
于 2013-06-28T06:43:40.857 回答