且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问套接字时如何设置超时时间?

更新时间:2023-02-26 18:27:09

如果您阅读了stream_set_timeout()的手册,就会知道stream_set_timeout()在超时情况下唯一要做的就是设置'timed_out' stream_get_meta_data()返回的数组的键为true.

If you'd read the manual for stream_set_timeout() you'd know that the only thing stream_set_timeout() does in case of timeout is setting of 'timed_out' key of the array returned by stream_get_meta_data() to true.

stream_set_timeout($fp, 5);
// set stream into non-blocking mode
stream_set_blocking($fp, false);

$break_counter = 0;
$result = '';
$info = stream_get_meta_data($fp);

while (!$info['timed_out'] && !feof($fp)) {
    $str = @fgets($fp, 1160);
    if ($str) {
        $result .= $str;
    } else {
        $break_counter += 1;

        if ($break_counter > 100) {
            break;
        }

        // 10000*100 microseconds gives you one second
        usleep(10000);
    }
    $info = stream_get_meta_data($fp);
}