I have a loop that accepts socket connections from clients. Each socket is a resource much like a file pointer is a resource or a database connection is a resource. I'm wondering if I can create an array to track my connected clients that uses the socket resource id as a key.
Currently, my code doesn't do that. As you can see here, I loop through my entire array of numerically-indexed clients every time sockets need reading and check to see if each of those clients is in the $sockets_to_read array.
while (true) {
/* specify which sockets need listening...should include
all connected client sockets *and* the main listening socket */
$this->sockets_to_read = array();
$this->sockets_to_read[0] = $this->main_listening_socket;
foreach ($this->clients as $client) {
if ($client['socket_id'] != NULL)
$this->sockets_to_read[] = $client['socket_id'];
}
/* Set up a blocking call to socket_select()...this call alters
the $sockets_to_xxxx arrays so that they indicate which sockets
need attention */
$num_changed_sockets = socket_select($this->sockets_to_read, $this->sockets_to_write, $this->sockets_to_except, $this->socket_select_timeout);
/* loop through all our clients and deal with those whose socket_ids
show up in the $this->sockets_to_read array */
foreach($this->clients as $client_key => $client) {
if (in_array($client['socket_id'] , $this->sockets_to_read)) {
$incoming_socket_data = socket_read($client['socket_id'], $this->socket_read_length, PHP_BINARY_READ);
// blah blah blah
}
// blah blah blah
}
}
I know this is really inefficient because I might have 40 connected clients and only 1 socket that needs reading, but I was worried about just doing something like
$new_client_resource = socket_accept($this->main_listening_socket); // echo $new_client_resource and it says something like "Resource #1"
$client = array();
$client['username'] = 'foo';
$client['rank'] = 'Admiral';
$this->clients[$new_client_resource] = $client; // warning! weirdness here. Is this an associative array? numeric? This looks weird to me.
I have a feeling that I could use the socket resource id as an array index and it would work but am wondering if that might cause weird problems that I can't foresee...like if a client disconnects and a new client connects and acquires a previously used resource id.
Any sage advice would be much appreciated.