0

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);
    ...
}
madshov
  • 653
  • 3
  • 9
  • 15

1 Answers1

0

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);
    ...
}
Vladimir
  • 99
  • 8
  • I did try something similar, but I keep getting `unable to connect: Transport endpoint is already connected` on the second iteration of create. Am I doing something wrong there? – madshov Sep 22 '18 at 16:07
  • how muh connections you required? Try to set value $backlog differ from 0 - socket_create(AF_INET, SOCK_STREAM, 128); – Vladimir Sep 22 '18 at 17:15
  • I'm not sure I understand. I'll need 10 connections. `socket_create` doesn't support 128 as protocol (3rd parameter). Right now my problem with the above seem to be that resource is not available when I read from the socket. I get `Resource temporarily unavailable`. – madshov Sep 22 '18 at 17:41