Socket concurrency in PHP

145 Views Asked by At

I would like to know if anyone has any good insight into how to open a number of sockets to the same server, write and then read data concurrently in PHP. Should I use a concurrency framework like Amphp or are there better options for this task? How would I go ahead and build this? Basically I want to achieve something like this in a nonblocking manner:

foreach ($conns as $c) {
    $socket = socket_create(AF_INET, SOCK_STREAM, 0);
    $result = socket_connect($socket, $c['host'], $c['port']);
    socket_write($socket, $c['message'], strlen($c['message']));
    $result = socket_read ($socket, 1024);
    socket_close($socket);
    ...
}
1

There are 1 best solutions below

3
Vladimir On

You write and read data sequentially in loop. Try to made two loops - in firest write and then in second read and names value of sockets in array:

$socket[] = socket_create(AF_INET, SOCK_STREAM, 0);
$result = socket_connect(current($socket), $c['host'], $c['port']);
socket_write(current($socket), $c['message'], strlen($c['message']));

In second loop read them and close:

foreach ($socket as $sc) {
    $result = socket_read ($sc, 1024);
    socket_close($sc);
    ...
}