微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP - fsockopen 函数超时不起作用

如何解决PHP - fsockopen 函数超时不起作用

我最近开始计时与服务器的连接。令人惊讶的是,有些调用甚至需要 10-20 秒,即使我的超时设置为 1 秒。我做错了什么?

$this->startTime = microtime(true); 

// Open connection
$socket = @fsockopen($this->host,$this->port,$errno,$errstr,1);
if (!$socket) {
    return false;
}

$this->endTime = microtime(true);
$this->time = ($this->endTime- $this->startTime);

@编辑

$connectionTimeStart = microtime(true); 

        // Open connection
        $socket = @fsockopen($this->host,1);

        $connectionTimeEnd = microtime(true);
        $this->connectionTime = ($connectionTimeEnd - $connectionTimeStart);

        if (!$socket) {
            return false;
        }

        $streamTimeStart = microtime(true); 

        // Get server info
        fwrite(MY FWRITE CODE);
        stream_set_timeout($socket,1);
        $response = stream_get_contents($socket);

        $streamTimeEnd = microtime(true);
        $this->streamTime = ($streamTimeEnd - $streamTimeStart);

        $info = stream_get_Meta_data($socket);
        fclose($socket);

        if ($info['timed_out']) {
            $this->timeout = true;
            return false;
        }

解决方法

如果您阅读了 fsockopen() 的文档:

https://www.php.net/manual/en/function.fsockopen.php

它说,这个超时参数只在连接到套接字时适用,但接收数据可以更长。

也使用stream_set_timeout()函数

https://www.php.net/manual/en/function.stream-set-timeout.php

PHP 文档非常清晰,当您使用函数时,只需花点时间阅读它即可了解您可以做什么和不可以做什么。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。