user1735111
user1735111

Reputation:

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

Upvotes: 1

Views: 367

Answers (1)

Armali
Armali

Reputation: 19375

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

Upvotes: 1

Related Questions