【问题标题】:php fsockopen fgets become too slowphp fsockopen fgets 变得太慢
【发布时间】:2011-10-11 14:50:22
【问题描述】:

我在尝试使用 fsockopen 和 fgets 获取网页内容时遇到问题。我可以很容易地从 Web 服务器接收标头,如下所示:

HTTP/1.1 200 OK 
[cache-control] => private 
[content-type] => text/plain; charset=utf-8 
[server] => Microsoft-IIS/7.0
[x-aspnet-version] => 2.0.50727
[x-powered-by] => ASP.NET
[date] => Sat, 23 Jul 2011 10:36:57 GMT
[connection] => close
[content-length]=> 30072 
[vary] => Accept-Encoding [content-encoding] => gzip

我的代码如下:

$fp = @fsockopen(“www.abc.com”, 80, $errno, $errstr, 30);
fwrite($fp, $request);//$request is my predefined header including path and cookies
$lines=””;
while (!feof($fp)) 
{
  Echo “fgets start at ”.date(“H:i:s”).”\n”;
  $line = fgets($fp, 4096);
  Echo strlen($line) .”\n”;
  Echo “fgets end at ”.date(“H:i:s”) .”\n”;
  $lines +=$line;
}
fclose($fp);

输出是这样的:

……
fgets start at 12:23:45
219
Fgets end at 12:23:47
……

我真的很想知道为什么只需要 2 秒才能获得 219 字节的数据。这太慢了。 要获取整个页面,包括数百个 fget 迭代,它需要花费 40 秒。而如果您使用 Firefox,则只需一秒钟..

我想知道是什么原因导致 fgets 变得太慢。

感谢您的阅读。

【问题讨论】:

  • 嗯,file_get_contents("www.abc.com")需要多少时间?
  • 你找到解决这个@cn2500的方法了吗?

标签: php performance header fgets fsockopen


【解决方案1】:

我脑子里一片空白:连接是否有可能因为您使用的是 HTTP/1.1 请求而保持打开状态?这将使服务器等待您发出另一个请求,然后如果没有找到则关闭连接(视为超时)。除此之外,您的操作系统可能正在缓冲数据(SO_RCVLOWAT socket_option),因此当 Web 服务器关闭连接时读取结束。

尝试减少循环内要读取的数据量(如 128 字节),看看会发生什么。除此之外(与此相关),您可能想尝试阅读以下内容:http://ar.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings

php 可能无法很好地阅读 EOL 的

【讨论】:

    猜你喜欢
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多