5

这是一些示例代码:

<?php
$fp = fsockopen($host, $port, $errno, $errstr, $connectTimeout);

if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    echo "connected\n"; 
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}

我见过 stream_set_timeout($fp, 5);and
socket_set_option($fp, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0));,但读取永远不会超时。

我在 PHP 文档中看到了几个警告stream_set_timeout()

此函数不适用于 stream_socket_recvfrom() 等高级操作,请改用带有 timeout 参数的 stream_select()。

我宁愿不使用select()或循环。进行超时阻塞读取的规范方法是什么?

4

1 回答 1

2

socket_set_option用于创建的套接字socket_create

stream_set_timeout用于流,例如由fopenor创建的fsockopen

Php 文档包含有关如何将其与 fsockopen 一起使用的示例代码。

于 2012-11-06T18:26:37.613 回答