深入解析fsockopen与pfsockopen的区别
前端之家收集整理的这篇文章主要介绍了
深入解析fsockopen与pfsockopen的区别,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
按手册上说,这两个函数的唯一区别是,
pfsockopen
是持续连接,而
fsockopen
不是.
我写了个代码了一下:
<div class="codetitle">
<a style="CURSOR: pointer" data="85712" class="copybut" id="copybut85712" onclick="doCopy('code85712')"> 代码如下: <div class="codebody" id="code85712">
<?
PHP $data="1,721,73,1,43290000,60D81D509BC00451,3,FFFFFFFF";
//
http://10.144.99.114/SANEX_NEW/modules/subscribemanager/test.
PHP$host = '127.0.0.1';
$url = "/aa.
PHP";
$pffirst = false;
$times = 1000;
$startTime = microtime(true);
for ($index = 0; $index < $times; $index++) {
echo httpPost($host,$url,$data,$pffirst)."
";
}
$middleTime = microtime(true);
for ($index = 0; $index < $times; $index++) {
echo httpPost($host,!$pffirst)."
";;
}
$endTime = microtime(true);
echo ($pffirst?"pfsocket":"fsocket").":".($middleTime-$startTime);
echo "
";
echo ($pffirst?"fsocket":"pfsocket").":".($endTime-$middleTime);$count=0;
//发包
函数function httpPost($host,$p)
{
global $count;
$func = $p?"pfsockopen":"fsockopen";$conn = $func($host,80,$errno,$errstr,30);
if (!$conn)
{
echo "$errstr ($errno)
\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);$count++;
echo $count.' '.$header."
";$resp='';
//while (!feof($conn)) {
//$resp .= fgets($conn);
//}
//fclose($conn);
return $resp;
}
?>
可以看出,fsocketopen默认每次处理结束后,就算协议头是Keep-Alive,连接仍然断掉了.
而pfsocketopen在Keep-Alive条件下,连接可以被下一次重复利用.