PHP Foreach 并行套接字连接?
我有一个脚本,它使用关联数组连接到 foreach 循环中的服务器列表,其中 ip 地址作为键,端口号作为值。我向套接字写入少量数据,然后从服务器读回响应。阵列中通常有 5-15 台服务器,每个事务可能需要几百毫秒,这会迅速增加用户的等待时间。有没有办法可以并行执行连接,以便用户不必等待很长时间?
foreach ($clients as $network_address => $port)
{
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
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);
}
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);
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 socket_select(数组 &$read 、数组 和$write 、数组 和$ except 、int *$tv_sec* [, int *$tv_usec* = 0 ]) 是与多个主机交谈的最佳方式。
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.