Man kann in PHP sehr schwer parallel Operationen ausführen, aber für das lesen von mehreren Sockets gibt es die socket_select() Funktion. Damit lassen sich mehrere Socket Verbindungen parallel auslesen.
In dem Beispiel werden 2 UDP Socket Verbindungen erstellt und gleichzeitig ausgelesen:
function createSocket(string $ip, int $port) { $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); //set non blocking read socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($socket, $ip, $port); if ($socket === false) { throw new \RuntimeException( sprintf( 'could not connect to socket address %s on port %s. Error: %s %s', $ip, $port, socket_last_error(), socket_strerror(socket_last_error()) ) ); } return $socket; }
function readSockets() { $waitTimeoutSeconds = 1; $socket1 = $this->createSocket('127.0.0.1', 20001); $socket2 = $this->createSocket('127.0.0.1', 20002); $sockets['socket1'] = $socket1; $sockets['socket2'] = $socket2; $read = $sockets; $write = null; $except = null; if (socket_select($read, $write , $except, $waitTimeoutSeconds)) { // loop through the sockets that showed activity if (isset($read['socket1'])) { // socket 1 got a message $content1 = socket_read ($socket1, 1024); } if (isset($read['socket2'])) { // socket 2 got a message $content2 = socket_read ($socket2, 1024); } } else { throw new \RuntimeException('could not read any socket'); } socket_close($socket1); socket_close($socket2); }