Read more UDP frames with PHP parallel with socket_select()


You can perform operations very difficult parallel in PHP, read but for which there are multiple sockets socket_select() Function. This way, more can be socket connections parallel readout.

The example 2 UDP socket connections created and at the same time read:

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);
}

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>