🦔

【PHP】HTTP/1 クライアントで stream_select を使う

2024/07/22に公開
<?php

$fp = stream_socket_client(
    "tcp://0.0.0.0:8000", $errno, $errstr, 10,
    STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT
);

stream_set_blocking($fp, false);
fwrite($fp, "GET / HTTP/1.1\r\n\r\n");

$read   = [$fp];
$write  = NULL;
$except = NULL;

while (true) {
    if (!stream_select($read, $write, $except, 10)) {
        continue;
    }

    foreach($read as $read_sock) {
        $input = fread($read_sock, 1024);

        if (empty($input)) {
            $key = array_search($read_sock, $read);
            unset($read[$key]);
            continue;
        }

        print($input);
    }

    if (!count($read)) {
        break;
    }
}

fclose($fp);

Discussion