简体   繁体   English

如何检查连接套接字上的数据是否可用?

[英]How Can I Check Whether Data Available at Connected Socket Or No?

When I send HTTP requests I want to use Connection: Keep-Alive when I need to send few requests one after the other. 当我发送HTTP请求时,我想使用Connection: Keep-Alive当我需要一个接一个地发送几个请求时。 How can I check whether the socket contains data? 如何检查套接字是否包含数据? my expected code: 我的预期代码:

    $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;
    }

It seems to me that you don't want to check whether the socket contains data (whatever that means), but to read the HTTP response and then continue. 在我看来,您不想检查套接字是否包含数据 (无论什么意思),而是要读取HTTP响应然后继续。 This can be accomplished by replacing the loop above: 这可以通过替换上面的循环来完成:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM