php长连接测试

本文介绍了一个使用PHP实现的网络请求测试脚本,该脚本通过两种不同的连接方式发送HTTP GET请求,并对比了持久连接(Keep-Alive)和关闭连接(Close)的性能差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



<?php
//http://i3.sinaimg.cn/home/07index/sinahome_wscfy_031.gif
//$url=http://10.69.2.206:8080/sms/ns2/save_msg.txt

function ohttp_get($host,$port,$query,&$body)
{
$fp=pfsockopen($host,$port,$errno,$errstr,1);
if(!$fp)
{
var_dump($errno,$errstr);
return -1;
}
$out = "GET /home/07index/sinahome_wscfy_031.gif HTTP/1.1\r\n";
$out.= "Host: ${host}\r\n";
$out.= "Connection: close\r\n";
$out.= "\r\n";
fwrite($fp,$out);

$line=trim(fgets($fp));
$header.=$line;
list($proto,$rcode,$result)=explode(" ",$line);
$len=-1;

while( ($line=trim(fgets($fp))) != "" )
{
$header.=$line;
if(strstr($line,"Content-Length:"))
{
list($cl,$len)=explode(" ",$line);
}
if(strstr($line,"Connection: close"))
{
$close=true;
}
}
if($len < 0)
{
echo "ohttp_get must cope with Content-Length header!\n";
return -1;
}
$body=fread($fp,$len);
if($close)
fclose($fp);
return $rcode;
}
function phttp_get($host,$port,$query,&$body)
{
$fp=pfsockopen($host,$port,$errno,$errstr,1);
if(!$fp)
{
var_dump($errno,$errstr);
return -1;
}
$out = "GET /home/07index/sinahome_wscfy_031.gif HTTP/1.1\r\n";
$out.= "Host: ${host}\r\n";
$out.= "Connection: Keep-Alive\r\n";
$out.= "\r\n";
fwrite($fp,$out);
$line=trim(fgets($fp));
$header.=$line;
list($proto,$rcode,$result)=explode(" ",$line);
$len=-1;

while( ($line=trim(fgets($fp))) != "" )
{
$header.=$line;
if(strstr($line,"Content-Length:"))
{
list($cl,$len)=explode(" ",$line);
}
if(strstr($line,"Connection: close"))
{
$close=true;
}
}
if($len < 0)
{
echo "phttp_get must cope with Content-Length header!\n";
return -1;
}
$body=fread($fp,$len);
if($close)
fclose($fp);
return $rcode;
}

$time1=microtime(true);
for($i=0;$i<100;$i++)
{
$host="i3.sinaimg.cn";
$port=80;
$query="/sms/ns2/save_msg.txt";
$body="";
$r=phttp_get($host,$port,$query,$body);
if($r != 200)
{
echo "return code : $r\n";
}
}
$time2=microtime(true);
for($i=0;$i<100;$i++)
{
$host="i3.sinaimg.cn";
$port=80;
$query="/sms/ns2/save_msg.txt";
$body="";
$r=ohttp_get($host,$port,$query,$body);
if($r != 200)
{
echo "return code : $r\n";
}
}
$time3=microtime(true);

echo "<br />";echo "<hr>";
echo "Time1:".$time1;echo "<br />";
echo "Time2:".$time2;echo "<br />";
echo "Time3:".$time3;echo "<br />";
echo "<br />";echo "<hr>";
echo "keep alive: ".($time2-$time1)."\n";
echo "close: ".($time3-$time2)."\n";

?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值