quinestor
quinestor

Reputation: 1442

Socket_select: it affects its inputs, but how exactly?

In the php documentation listed here there's an indication that the function uses the read, error and write array values as refference but I have failed to find anywhere what is actually changed in those values.

I wrote a simple 'server' I use now and I noted that when the mentioned function fails to see any data on the polled clients, then it changes the array and renders it unusable to poll again. This is my code:

<php - all socket creation binding and listening above..
socket_set_nonblock($mysock);

$w = $e = array();
$clients = array($mysock);

do {
    $temp_client = @socket_accept($mysock);
    if ($temp_client != FALSE) 
        $clients[] = $temp_client;

    $clients_backup = $clients;

    $select_socket = socket_select($clients,$w,$e,0);
    if (($select_socket !== FALSE) AND ($select_socket != 0)) {
        foreach ($clients as $value) {
            $input = socket_read($value,1024,PHP_BINARY_READ);
            echo $input;
        }
    }
    $clients = $clients_backup;
} while(TRUE);

When testing this consider that the first connection is not handled.. I have no idea why (would very much thank elightment) this code is a strip of what I'm developing and there it works ok. The socket_select issue remains the same in both codes.

Basically If I do not make that backup of the clients array, it doesn't work. The error: "no resource arrays were passed to select" is seen since the array doesn't have the socket resource after socket_select first checks a connection with no data to read.

Upvotes: 2

Views: 1673

Answers (1)

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28929

These arrays are arrays of socket resources. socket_select() will modify the arrays by removing from them any resources that aren't ready to be read from, written to, etc., respectively.

You'll almost always want to pass it copies of your arrays, because they will be modified, and you don't want to lose your original references to them:

$clients = [ ... ];
$r = $w = $e = $clients;

$numChanged = socket_select($r, $w, $e, ...);

// Here, $r, $w, and $e will only contain the resources that are ready for processing, which may be none at all

Upvotes: 4

Related Questions