2

我打开多个(75)个流stream_socket_client(),然后用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 秒甚至更短。

4

1 回答 1

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

于 2018-09-14T14:05:02.710 回答