(PHP 4 >= 4.1.0, PHP 5)
socket_select — Führt einen select()-Systemaufruf auf den gegebenen Socket-Arrays aus, wobei ein Zeitlimit bestimmt wird
socket_select() nimmt als Parameter Socket-Arrays entgegen und wartet, ob diese ihren Status ändern. Diejenigen, die Hintergrundwissen über BSD-Sockets haben, werden feststellen, dass diese Socket-Arrays in Wirklichkeit die sogenannten Datei-Deskriptor-Mengen sind. Drei voneinander unabhängige Arrays mit Socket-Deskriptoren werden überwacht.
Die Sockets, die im read-Array aufgelistet sind, werden daraufhin überwacht, ob Zeichen zum Auslesen zur Verfügung gestellt werden. (Um genauer zu sein: es wird überwacht, ob ein Lesevorgang blockiert - ein Socket ist nämlich auch dann bereit, wenn er bis zum Dateiende gelesen hat. In diesem Fall gibt socket_read() einen leeren String zurück.)
Die Sockets, die im write-Array aufgelistet sind, werden daraufhin überwacht, ob ein Schreibvorgang blockiert.
Die Sockets, die im except-Array aufgelistet sind, werden auf Ausnahmen überwacht.
tv_sec und tv_usec bilden zusammen den timeout-Parameter. Der timeout ist eine obere Schranke für die Zeit, die verstreichen kann, bis socket_select() zurückkehrt. tv_sec kann 0 sein, wodurch socket_select() sofort zurückkehrt. Dies ist nützlich beim Polling. Falls der Parameter tv_sec NULL ist (kein Timeout), kann socket_select() unendlich lange blockieren.
Beim Beenden werden alle Arrays aktualisiert, und zeigen an, welche Sockets ihren Status geändert haben.
Sie brauchen nicht jedes Array einzeln an socket_select() übergeben. Sie können die Arrays auch weglassen und stattdessen leere Arrays oder NULL angeben. Vergessen Sie nicht, dass diese Arrays by reference übergeben werden müssen und dass sie verändert werden, nachdem die Funktion socket_select() beendet ist.
Hinweis:
Wegen einer Einschränkung in der aktuellen Zend Engine ist es nicht möglich, eine Konstante, wie etwa NULL, direkt als Parameter an Funktionen zu übergeben, die ihre Argumente als Referenzen erwarten. Sie können stattdessen eine temporäre Variable oder einen Ausdruck, in dem der am weitesten links stehende Teilausdruck eine temporäre Variable ist, benutzen.
Beispiel #1 NULL mit socket_select() benutzen:
<?php
$e = NULL;
socket_select($r, $w, $e, 0);
?>
Bei Erfolg gibt socket_select() die Anzahl der Socket-Deskriptoren zurück, die in den aktualisierten Arrays enthalten sind. Falls der Timeout wirksam wird, bevor irgend etwas Interessantes passiert, ist das Funktionsergebnis 0. Falls ein Fehler auftritt, wird FALSE zurückgegeben. Der Fehlercode kann dann mit socket_last_error() abgefragt werden.
Hinweis:
Wenn Sie einen Fehler aufspüren wollen, müssen Sie unbedingt den Operator === benutzen. Weil socket_select() auch 0 zurückgeben kann, wird der Vergleich mit == sonst zu TRUE ausgewertet.
Beispiel #2 Rückgaben von socket_select() verstehen
<?php
$e = NULL;
if (false === socket_select($r, $w, $e, 0)) {
echo "socket_select() fehlgeschlagen, Grund: " .
socket_strerror(socket_last_error()) . "\n";
}
?>
Beispiel #3 socket_select()-Beispiel
<?php
/* Das Array read vorbereiten */
$read = array($socket1, $socket2);
$write = NULL;
$except = NULL;
$num_changed_sockets = socket_select($read, $write, $except, 0);
if ($num_changed_sockets === false) {
/* Fehlerbehandlung */
} else if ($num_changed_sockets > 0) {
/* Mindestens an einem Socket ist etwas Interessantes passiert */
}
?>
Hinweis:
Seien Sie sich bewusst, dass manche Socket-Implementierungen sehr sorgfältig benutzt werden müssen. Ein paar grundsätzliche Regeln:
- Sie sollten immer versuchen, socket_select() ohne Timeout zu benutzen. Ihr Programm sollte nichts tun, wenn keine Daten verfügbar sind. Code, der von Zeitbegrenzungen abhängig ist, ist normalerweise nicht portierbar und schwierig zu debuggen.
- Es sollte kein Socket-Deskriptor in die Arrays eingefügt werden, wenn Sie nicht vorhaben, die Ergebnisse nach der Ausführung von socket_select() zu prüfen und entsprechend darauf zu reagieren. Nachdem socket_select() beendet ist, müssen alle Sockets in allen Socket-Arrays geprüft werden. Jeder Socket, der zum Schreiben zur Verfügung steht, muss beschrieben werden und aus jedem Socket, der zum Lesen verfügbar ist, muss gelesen werden.
- Bei Schreib-/Leseoperationen auf den Sockets in den Arrays müssen Sie damit rechnen, dass nicht notwendigerweise alle Daten geschrieben/gelesen werden, die Sie angeben. Seien Sie darauf vorbereitet, dass Sie möglicherweise nur ein einziges Byte schreiben/lesen können.
- Fast allen Socket-Implementierungen ist gemeinsam, dass sie nur eine einzige Ausnahme in dem Array except auffangen können. Und zwar, wenn bandexterne Daten von einem Socket empfangen werden.
The way the document describes socket_select()'s handling of sockets polled for read is rather obscure.
It says that it checks to see if reading would not "block," but the overall description of socket_select() says it checks for a change in blocking status. Unfortunately, these are in conflict.
If a socket already has data in the buffer, calling socket_select() on that socket would never return (assuming null timeout), and would block forever. :-( This is because the blocking status wouldn't change. It simply stays "non-blocking"
It is important to remember NOT to select() on a socket which may already have data available.
An example...
<?php
//... $socket is already here...
$done = false;
$n = 0;
do{
$tmp = 0;
$r = $w = $e = array();
$r = array($socket);
socket_select($r,$w,$e,null);
$n = socket_recv($socket, $tmp, 1024, 0);
//$done = true; //Something determines that we are done reading...
}while(!$done);
?>
This MAY NOT work... socket_select() is always being called... but we may have data in the input buffer.
We need to ensure that the last time we read, nothing was read... (empty buffer)
<?php
//... $socket is already here...
$done = false;
$n = 0;
do{
$tmp = 0;
$r = $w = $e = array();
$r = array($socket);
if($n === 0) socket_select($r,$w,$e,null);
$n = socket_recv($socket, $tmp, 1024, 0);
//$done = true; //Something determines that we are done reading...
}while(!$done);
?>
If you using a Flash client - you should know some specific features:
1) when client connects to the server - it is sending to you "<policy-file-request/>"."\0" string. Server should answer an XML policy file, then disconnect from this client. Code is something like
if ('<policy-file-request/>'==substr($data, 0, 22))
{
echo "policy requset.\n";
flush();ob_flush();
$msg = '<'.'?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" to-ports="*" />
</cross-domain-policy>'."\0";
echo "Say to client (crossdomain.xml) ... ";
flush();ob_flush();
socket_write($read_sock, $msg, strlen($msg));
echo "OK\n";
flush();ob_flush();
echo "Closing ... ";
flush();ob_flush();
socket_close($read_sock);
echo "OK\n";
flush();ob_flush();
}
else
{
// here is normal IO operations with client
}
2) every output to client should be ended with "\0" (if using XMLSocket in Flash client) - otherwise flash will not generate onData event
Russian examples is there - http://www.flasher.ru/forum/showpost.php?p=901346&postcount=7
socket_select() can also serve as a more granular sleep():
<?php
# half-second sleep
$undef = array();
socket_select($undef, $undef, $undef, 0, "500000");
?>
Just noticed that you have to loop socket_select () when using UDP to get all queued packets:
<?php
while (socket_select ($aRead, $aWrite, $aExcept, 1) > 0) {
foreach ($aReadUdp as $oSocket) {
$this->clientReadUdp ($oSocket);
}
}
?>
That's important because every call of socket_select () on UDP brings you only one result. But there could be 10.000 results queued and if your turnarround time is to slow (server busy, other sleeps etc.), you'll never progress all results in near realtime.
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.
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));
?>
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();
}
?>
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 */
}
?>
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.
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);
?>
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'
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.
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.
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
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;
}
}
?>