开发者

PHP Foreach Parallel Socket Connections?

I have a script that connects to a list of servers in a foreach loop using an associative array with the ip address as the key and port number as the value. I write a small amount of data to the socket then read back the response from the server. There are usually 5-15 servers in the array and each transaction can take a few hundred milliseconds which quickly adds to the waiting time for the user. Is there a way I can execute the connections in parallel so the users don't have to wait as long?

foreach ($clients as $network_address => $port)
{
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
 开发者_Python百科   if ($socket === false) {
        continue;
    }

    $result = socket_connect($socket, $network_address, $port);
    if ($result === false) {
        continue;
    }

    socket_write($socket, $data, strlen($data));

    $response[$network_address] = socket_read($socket, 2048);

    socket_close($socket);
}


Using socket_select(array &$read , array &$write , array &$except , int *$tv_sec* [, int *$tv_usec* = 0 ]) is the best way, to talk to more then one host.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜