通过特定端口(fsockopen)在PHP中检测服务器连通性
这个函数叫做 checkServer,它接受两个参数:一个是域名($domain),另一个是端口($port),默认是80。
$status = 0;
$starttime = microtime(true);
$file = @fsockopen ($domain, $port, $errno, $errstr, $checkTimeout);
$stoptime = microtime(true);
if($file)
{
fclose($file);
$status = ($stoptime - $starttime) * 1000;
$status = floor($status);
}
else
{
$testfile = @fsockopen ($testServer, 80, $errno, $errstr, $checkTimeout);
if($testfile)
{
fclose($testfile);
$status = -1;
}
else
{
$status = -2;
}
}
return $status;
}
这里的测试服务器是 google.sk,检查超时时间是10秒。这个函数实际上是可以工作的,但当我尝试把它循环运行大约50次,并且同时做其他事情(比如数据库查询等),虽然速度没有变慢,但我的CPU使用率却达到了100%,直到脚本结束。这个过程是由一个apache进程在运行,搞得我的CPU非常忙……所以我想问问你们有没有什么好的建议。也许如果你能给我一些用Python或Bash实现相同功能的提示,我会很感激。
谢谢大家的回复 :)