[英]PHP - fsockopen function timeout not working
I have recently started timing the connection to the server.我最近开始计时与服务器的连接。 Surprisingly, some calls take even 10-20 seconds, even though my timeout is set to 1 second.
令人惊讶的是,有些呼叫甚至需要 10-20 秒,即使我的超时设置为 1 秒。 What am I doing wrong?
我究竟做错了什么?
$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);
@EDIT @编辑
$connectionTimeStart = microtime(true);
// Open connection
$socket = @fsockopen($this->host, $this->port, $errno, $errstr, 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;
}
If you read docs for fsockopen()
:如果您阅读
fsockopen()
的文档:
https://www.php.net/manual/en/function.fsockopen.php https://www.php.net/manual/en/function.fsockopen.php
It says, this timeout parameter only applies while connecting to a socket, but receiving data can be longer.它说,这个超时参数只适用于连接到套接字时,但接收数据可以更长。
Use stream_set_timeout()
function too也使用
stream_set_timeout()
function
https://www.php.net/manual/en/function.stream-set-timeout.php https://www.php.net/manual/en/function.stream-set-timeout.php
PHP docs is quite clear, just take time to read it when you use a function to know what you can do and what you can't. PHP 文档非常清楚,当您使用 function 时,请花时间阅读它,以了解您能做什么和不能做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.