【问题标题】:stream_set_timeout() does not work in PHP?stream_set_timeout() 在 PHP 中不起作用?
【发布时间】:2013-08-21 04:55:08
【问题描述】:

stream_set_timeout() 是否有可能不起作用?我的功能(下面的代码)只要服务器需要回复。如果服务器需要 30 秒才能回复,该函数会耐心等待。我希望它在几秒钟后超时,函数应该返回 null 并且网站不应该加载超过 30 秒,而是告诉存在连接问题。 我正在使用 PHP 5.4。

function request($json){
    $reply = null;
    $fp = @fsockopen("localhost", 1234, $errno, $errstr, 2);
    if(!$fp){
        return null;
    }
    fputs($fp, $json."\r");
    stream_set_timeout($fp, 2);
//  stream_set_blocking($fp, true); <-- I've read in a related SO question that this might help. It doesn't.
    for($i=0; !feof($fp); $i++){
        $reply = fgets($fp);
    }
    fclose($fp);
    return $reply;
}

【问题讨论】:

  • 尝试将stream_set_timeout 放在fputs 之前。
  • 我已经尝试过了。没有帮助。发送不是问题,接收才是问题,因为服务器必须准备数据。

标签: php


【解决方案1】:

它不起作用,因为您没有检查fgets() 的返回值,也没有检查套接字元数据。发生超时时,套接字不会被标记为 EOF。

以下代码应该更适合您:

$i = 0;
while (!feof($fp)) {
    if (($reply = fgets($fp)) === false) {
        $info = stream_get_meta_data($fp);
        if ($info['timed_out']) {
             // timed out
        } else {
             // some other error
        }
    }
    ++$i;
}

【讨论】:

  • 这与将stream_set_blocking() 设置为true 一起完成!谢谢你:)
猜你喜欢
  • 2013-07-02
  • 2012-11-05
  • 1970-01-01
  • 2016-05-25
  • 2017-06-18
  • 2018-07-31
  • 2013-03-16
  • 2018-07-06
  • 2011-01-14
相关资源
最近更新 更多