User Contributed Notes 19 notes

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

// set the option to reuse the portsocket_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 connectionssocket_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 iterationif (socket_select($read, $write = NULL, $except = NULL, 0) < 1) continue;

// check if there is a client trying to connectif (in_array($sock, $read)) {// accept the client, and add him to the $clients array$clients[] = $newsock = socket_accept($sock);

// send the client a welcome messagesocket_write($newsock, "no noobs, but ill make an exception :)\n"."There are ".(count($clients) - 1)." client(s) connected to the server\n");

// loop through all the clients that have data to read fromforeach ($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);

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.

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)

while (true) {// Make list of sockets to listen for changes in, including host$read = array($host_socket);

// get a list of all the clients that have data to be read from$ready=@socket_select($read, $write = NULL, $except = NULL,0); if ($ready=== false) die("Failed to listen for clients: ". socket_strerror(socket_last_error()));

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():

As it was already said, some clients need \0 character to end transmission, for example Flash's XMLSocket.

You should also be prepared to read less data than you have requested.

Here is an example of a socket buffer - it's an array which has socket resources for keys and an array of a timestamp and recieved data as values.

I find that the best practice for sending data is trailing it with a new line and zero character (\n\0), because you will probably have different types of clients which behave differently for reading data from sockets. Some need a \n to fire an event, some need \0.

For recieving data, sometimes you will get splitted data - this can hapen because the buffer is full (in my example 8192 bytes) or it just gets broken during transmission in lower levels.

Sometimes you can read two messages at once, but they have a zero character in between, so you can just use preg_split() to split the messages. The second message may not be complete, so you add it to your buffer.

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.

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.

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