fsockopen,读返回数据不易采用feof函数
两天辛苦,得出一个结论:用feof函数判断读socket返回是否结束,是非常错误的做法。效率之低,耗时之久,实在让人忍无可忍。
写一断测试代码:
<?php
function httpPost($host,$url,$data,$p)
{
$conn = fsockopen($host,80,$errno, $errstr, 30);
if (!$conn)
{
echo "$errstr ($errno)<br />\n";
return;
}
$header = "POST ".$url." HTTP/1.1\r\n";
$header.= "Host : {$host}\r\n";
$header.= "Content-type: application/x-www-form-urlencoded\r\n";
$header.= "Content-Length:".strlen($data)."\r\n";
$header.= "Connection: Keep-Alive\r\n\r\n";
$header.= "{$data}\r\n\r\n";
fwrite($conn,$header);
//读内容
$resp='';
$start = microtime(true);
echo "开始读<br>";
while (!feof($conn)) {
echo "读之前:".(microtime(true)-$start)."<br>";
$resp .= fread($conn,64);
echo "读之后:".(microtime(true)-$start)."<br>";
}
echo "内容:".$resp."<br>";
echo "读完关闭前:".(microtime(true)-$start)."<br>";
fclose($conn);
echo "关闭:".(microtime(true)-$start)."<br>";
return $resp;
}
httpPost("127.0.0.1","/aa.php","test",true);
?>
输出结果:
开始读
读之前:4.4822692871094E-5
读之后:0.00069689750671387
读之前:0.00070381164550781
读之后:0.00070691108703613
读之前:0.00070881843566895
读之后:0.00071382522583008
读之前:0.00071597099304199
读之后:5.531320810318
内容:HTTP/1.1 200 OK Date: Sat, 28 Aug 2010 03:35:20 GMT Server: Apache/2.2.15 (Win32) PHP/5.2.12 X-Powered-By: PHP/5.2.12 Content-Length: 5 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/html hello
读完关闭前:5.5313439369202
关闭:5.531445980072
可以看到,读最后一条数据时,耗时达5秒之多。
另一种方法,见续篇
http://baiyuxiong.iteye.com/admin/blogs/758754