在PHP中对流进行读取超时的规范方法是什么?

时间:2012-10-18 23:33:24

标签: php sockets

以下是一些示例代码:

<?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);
socket_set_option($fp, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0));, 但阅读永远不会超时。

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

  

此功能不适用于高级操作   stream_socket_recvfrom(),改为使用带有超时参数的stream_select()。

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

1 个答案:

答案 0 :(得分:2)

socket_set_option适用于使用socket_create创建的套接字。

stream_set_timeout适用于由fopenfsockopen创建的流。

Php docs包含有关如何与fsockopen一起使用的示例代码。

相关问题