Just to add to this. Since the information contained in the notes is somewhat old. It appears keys are being preserved now.
So, if you rely on knowing which keys need to be worked with and were like me and thought that it didnot preserve. Well it does.
socket_select
(PHP 4 >= 4.0.7, PHP 5)
socket_select — Exécute l'appel système select() un tableau de sockets avec une durée d'expiration
Description
socket_select() accepte un tableau de sockets et attend qu'elles changent de statut. Ceux qui sont familiers avec les sockets de BSD reconnaîtront dans ces tableaux de sockets les jeux de pointeurs de fichiers. Trois tableaux indépendants de ressources de sockets sont surveillés.
Liste de paramètres
- read
-
Les sockets listées dans le paramètre read seront surveillées en lecture : pour savoir quand elles sont disponibles en lecture (plus précisément, si une lecture ne va pas bloquer, en particulier, une ressource de socket a déjà atteint une fin de fichier, auquel cas socket_read() retournera une chaîne de taille zéro).
- write
-
Les sockets listées dans write seront surveillées en écriture : pour voir si une écriture ne va pas bloquer.
- except
-
Les sockets listées dans except seront surveillées pour leurs exceptions.
- tv_sec
-
Les paramètres tv_sec et tv_usec ensembles forment le paramètre timeout (durée de vie). Le timeout est la durée maximale de temps avant que socket_select() ne se termine. tv_sec peut être zéro, ce qui fera que socket_select() retournera immédiatement. C'est très pratique pour faire du polling (sondage). Si tv_sec est NULL (pas de timeout), socket_select() peut se bloquer indéfiniment.
- tv_usec
-
En sortie de fonction, les tableaux sont modifiées pour indiquer quelles sockets ont changé d'état.
Vous n'avez pas besoin de passer tous les tableaux à socket_select(). Vous pouvez les omettre, ou utiliser un tableau vide, ou encore NULL à la place. N'oubliez pas que ces tableaux sont passés par référence et seront modifiés par socket_select().
Note: À cause d'une limitation du moteur Zend actuel, il n'est pas possible de passer une constante comme NULL directement comme paramètre à cette fonction, qui attend une valeur par référence. À la place, utilisez un tableau temporaire ou une expression dont le membre de gauche est une variable temporaire :
Exemple #1 Passer NULL à socket_select()
<?php
$e = NULL;
socket_select($r, $w, $e, 0);
?>
Valeurs de retour
En cas de succès, socket_select() retourne le nombre de sockets contenues dans les tableaux modifiés. Ce nombre peut être zéro si la durée maximale d'attente a été atteinte. En cas d'erreur, FALSE est retourné. Le code d'erreur généré peut être obtenu en appelant la fonction socket_last_error().
Note: Assurez-vous bien d'utiliser l'opérateur === lorsque vous vérifiez les erreurs. Étant donnée que socket_select() peut retourner 0, la comparaison avec FALSE via == donnerait TRUE :
Exemple #2 Analyser le résultat de socket_select()
<?php
$e = NULL;
if (false === socket_select($r, $w, $e, 0)) {
echo "socket_select() a échoué. Raison : " .
socket_strerror(socket_last_error()) . "\n";
}
?>
Exemples
Exemple #3 Exemple avec socket_select()
<?php
/* Prépare le tableau read (socket surveillées en lecture) */
$read = array($socket1, $socket2);
$write = NULL;
$except = NULL;
$num_changed_sockets = socket_select($read, $write, $except, 0);
if ($num_changed_sockets === false) {
/* Gestion des erreurs */
} else if ($num_changed_sockets > 0) {
/* Au moins une des sockets a été modifiée */
}
?>
Notes
Note: Méfiez-vous des implémentations de sockets, qui doivent être manipulées avec délicatesse. Quelques règles de base :
- Vous devez toujours essayer d'utiliser socket_select() sans timeout. Votre programme ne devrait avoir rien à faire si il n'y a pas de données disponibles. Le code qui dépend d'un timeout est généralement peu portable, et difficile à déboguer.
- Une socket ne doit pas être ajoutée à l'un des tableaux en paramètre, si vous ne souhaitez pas vérifier le résultat après l'appel à socket_select(). Après le retour de socket_select(), toutes les sockets dans tous les tableaux doivent être vérifiées. Toute socket qui est disponible en écriture ou en lecture doit être utilisée pour écrire ou lire.
- Si vous écrivez ou lisez avec une socket retournée dans un tableau, soyez conscient qu'elle ne pourra pas écrire ou lire toutes les données que vous demandez. Soyez prêt à ne pouvoir lire qu'un seul octet.
- Il est commun à la plupart des implémentations de socket que la seule exception interceptée par les sockets dans le tableau except soit le cas des données hors limites, reçues par une socket.
socket_select
16-Sep-2008 06:45
30-Nov-2007 10:38
In regards to the code posted by vardhan ( at ) rogers ( dot ) com, it appears that on the following line:
if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)
the timeout parameter is accidentally set to 0, rather than NULL. This means that the select call will return immediately rather than blocking indefinitely.
Change the socket_select line to the following for great success:
if (socket_select($read, $write = NULL, $except = NULL, NULL) < 1)
If you want to use a simple fractional value for timeout:
<?php
socket_select(..., floor($timeout), ceil($timeout*1000000));
?>
20-Apr-2006 04:35
Another solution to the problem of keys not being preserved is to have an additional array for looking up sockets that uses their resource identifiers as keys. This can be obtained using array_flip() in some cases, but is particularly useful if each socket is associated with an object. In this case, you can make the object's constructor add a pointer to itself to the lookup array with its socket resource identifier as a key and use the following code to execute a read method for the object associated with each socket returned by socket_select():
<?php
socket_select($reads, $writes, $excepts, 0);
foreach ($sockets as $socket) {
$lookuparray[$socket]->read();
}
?>
02-Nov-2005 02:35
Regarding the comment below, No, it does not, it's a system call and I believe it's rather hard to preserve keys.
Additionally, socket_select should be used like it was a user-inputted array, that you don't know what you sent in to.
<?php
$reads = $clients;
$reads[] = $server;
socket_select($reads);
foreach ($reads as $read) {
/* do some stuff */
}
?>
01-Oct-2005 01:15
Note that the resulting arrays do NOT maintain keys (PHP 4.3.2) after being run through this function:
Before:
Array
(
[Client_Socket] => Resource id #6
[Server_Socket] => Resource id #9
)
After:
Array
(
[0] => Resource id #6
[1] => Resource id #9
)
It would have been nice to have the keys stay to figure out which stream you need to receive from, but you'll have to use some fancy foreach loop to figure out which sockets to check.
28-Aug-2005 04:46
A simple PHP script using socket_select() to manage multiple connections.
connect using "telnet localhost 9050". it broadcasts your messages that you send through telnet to other users connected to the server -- sort of like a chat script
#!/usr/local/bin/php
<?php
$port = 9050;
// create a streaming socket, of type TCP/IP
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// set the option to reuse the port
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
// "bind" the socket to the address to "localhost", on port $port
// so this means that all connections on this port are now our resposibility to send/recv data, disconnect, etc..
socket_bind($sock, 0, $port);
// start listen for connections
socket_listen($sock);
// create a list of all the clients that will be connected to us..
// add the listening socket to this list
$clients = array($sock);
while (true) {
// create a copy, so $clients doesn't get modified by socket_select()
$read = $clients;
// get a list of all the clients that have data to be read from
// if there are no clients with data, go to next iteration
if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)
continue;
// check if there is a client trying to connect
if (in_array($sock, $read)) {
// accept the client, and add him to the $clients array
$clients[] = $newsock = socket_accept($sock);
// send the client a welcome message
socket_write($newsock, "no noobs, but ill make an exception :)\n".
"There are ".(count($clients) - 1)." client(s) connected to the server\n");
socket_getpeername($newsock, $ip);
echo "New client connected: {$ip}\n";
// remove the listening socket from the clients-with-data array
$key = array_search($sock, $read);
unset($read[$key]);
}
// loop through all the clients that have data to read from
foreach ($read as $read_sock) {
// read until newline or 1024 bytes
// socket_read while show errors when the client is disconnected, so silence the error messages
$data = @socket_read($read_sock, 1024, PHP_NORMAL_READ);
// check if the client is disconnected
if ($data === false) {
// remove client for $clients array
$key = array_search($read_sock, $clients);
unset($clients[$key]);
echo "client disconnected.\n";
// continue to the next client to read from, if any
continue;
}
// trim off the trailing/beginning white spaces
$data = trim($data);
// check if there is any data after trimming off the spaces
if (!empty($data)) {
// send this to all the clients in the $clients array (except the first one, which is a listening socket)
foreach ($clients as $send_sock) {
// if its the listening sock or the client that we got the message from, go to the next one in the list
if ($send_sock == $sock || $send_sock == $read_sock)
continue;
// write the message to the client -- add a newline character to the end of the message
socket_write($send_sock, $data."\n");
} // end of broadcast foreach
}
} // end of reading foreach
}
// close the listening socket
socket_close($sock);
?>
01-May-2005 10:13
The continuation of my my previous post on 28-Apr-2005 10:19 at
http://ca3.php.net/manual/en/function.socket-select.php
Here it is: (Link is broken into 2 parts)
'http://gtkphp.org/php_socket_select_hangs
_explanation_and_solution.html'
16-Sep-2004 06:37
It is probably a bad idea to watch an array of sockets for input with socket_select, and then socket_read() using PHP_NORMAL_READ.
Although this seems desirable, you can end up with a permanently blocked program, if someone sends you malformed input which is missing a trailing \n \r. Guess how I found that out.
14-Feb-2003 01:36
Please note that the timeout parameter has important side-effects on the CPU usage of your script.
Setting the timeout to 0 will make your CPU looping without any time to have some rest and handle other running processes on your system, causing the system load to increase heavily while your script is running.
Personnaly, I use a value of 15 ms for this parameter. this ensures a good listening frequency while letting your system load clear.
Example :
$read = array($ListeningSocket);
$num_changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0, 10);
Hope this helps.
09-Sep-2002 06:27
If you haven't done any network programming before, PHP's socket_select() might appear a bit strange to you. I've written a simple php "partyline" script to demonstrate the multi-socket use of select'ing at http://dave.dapond.com/socketselect.php.txt
09-Jul-2002 07:15
hello,
i just made a class which acts similiar to Perl's IO::Select in order to make socket selecting very easy
your script should look something like that:
<?php
$server = new Server;
$client = new Client;
for (;;) {
foreach ($select->can_read(0) as $socket) {
if ($socket == $client->socket) {
// New Client Socket
$select->add(socket_accept($client->socket));
}
else {
//there's something to read on $socket
}
}
}
?>
you should of course implement some routines to detect broken sockets and remove them from the select object.
you can also do output buffering and check in the main-loop for sockets that are ready to write
<?php
class select {
var $sockets;
function select($sockets) {
$this->sockets = array();
foreach ($sockets as $socket) {
$this->add($socket);
}
}
function add($add_socket) {
array_push($this->sockets,$add_socket);
}
function remove($remove_socket) {
$sockets = array();
foreach ($this->sockets as $socket) {
if($remove_socket != $socket)
$sockets[] = $socket;
}
$this->sockets = $sockets;
}
function can_read($timeout) {
$read = $this->sockets;
socket_select($read,$write = NULL,$except = NULL,$timeout);
return $read;
}
function can_write($timeout) {
$write = $this->sockets;
socket_select($read = NULL,$write,$except = NULL,$timeout);
return $write;
}
}
?>
