我通过stream_socket_client()
打开多个(75)流,然后用stream_select()
处理它。这种方法的第一次调用需要大约。 15秒,我不明白为什么。下一次调用要快得多 - 整个方法少于一秒或两秒。我已经将问题跟踪到连接打开的foreach,这本身需要14/15秒。
码:
foreach ($tlds as $index => $server ) {
$ip = gethostbyname($server);
$con = @stream_socket_client($ip.':43',$errno, $errstr, 10, STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT);
usleep(200);
if (!$con) {
$fails[] = $server;
} else {
$calls[$index] = $con;
stream_set_blocking($calls[$index], false);
}
//get time here
}
测试结果:
╔════════╦══════════╦══════════╗
║ $index ║ 1st call ║ 2nd call ║
╠════════╬══════════╬══════════╣
║ 0 ║ 5s ║ 0s ║
╠════════╬══════════╬══════════╣
║ 10 ║ 6s ║ 0s ║
╠════════╬══════════╬══════════╣
║ 20 ║ 7s ║ 0s ║
╠════════╬══════════╬══════════╣
║ 30 ║ 9s ║ 0s ║
╠════════╬══════════╬══════════╣
║ 40 ║ 11s ║ 0s ║
╠════════╬══════════╬══════════╣
║ 50 ║ 12s ║ 0s ║
╠════════╬══════════╬══════════╣
║ 60 ║ 13s ║ 0s ║
╠════════╬══════════╬══════════╣
║ 70 ║ 14s ║ 1s ║
╠════════╬══════════╬══════════╣
║ end ║ 14s ║ 1s ║
╚════════╩══════════╩══════════╝
我对套接字编程没有经验,所以我很感激任何提示。
PHP 7.1,Apache / 2.4.6(CentOS)
询问您需要的任何信息 - 希望我能够回答。
注意:有时第二次通话大约需要第一次通话的1/3。但接下来的电话大约是1秒甚至更短。
我认为你有DNS延迟问题。您可以在循环中尝试使用linux控制台来检测它。
time nslookup $server
如果确认dns很慢,则可以使用NSCD服务进行本地记录缓存。在CENTOS:yum -y install nscd;systemctl enable nscd;systemctl start nscd;
和重启后的httpd服务。来自nscd:/usr/sbin/nscd -g
的统计数据