fsockopen,读返回数据不易采用feof函数

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秒之多。
另一种方法,见续篇[url]http://baiyuxiong.iteye.com/admin/blogs/758754[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值