Skip to content

Instantly share code, notes, and snippets.

@nmmmnu
Created November 30, 2011 08:32
Show Gist options
  • Save nmmmnu/1408434 to your computer and use it in GitHub Desktop.
Save nmmmnu/1408434 to your computer and use it in GitHub Desktop.
PHP based select() server
<?
/*
This is server written in PHP that employ socket select() method.
It is single threaded and does not fork, but rather process the clients "very" fast one by one.
Redis, nginx and Lighttpd works in similar way.
This source was found on the net, but I did lots of changes in order to get it work.
To make things simple, server is changed to be echo server, it simply print back what you send.
After starting the file, you should do:
telnet 127.0.0.1 5000
and type something.
*/
// Based on
// http://devzone.zend.com/209/writing-socket-servers-in-php/
// Set the ip and port we will listen on
$address = '0.0.0.0';
$port = 5000;
$max_clients = 10;
// Array that will hold client information
$clients = Array();
// Create a TCP Stream socket
$master_socket = socket_create(AF_INET, SOCK_STREAM, 0);
// Bind the socket to an address/port
socket_bind($master_socket, $address, $port);
// Start listening for connections
socket_listen($master_socket);
// master loop
while (true) {
// Setup clients listen socket for reading
$read = array();
$read[] = $master_socket;
// Add clients to the $read array
foreach($clients as $client){
$read[] = $client;
}
// Set up a blocking call to socket_select()
$ready = socket_select($read, $read_null = null, $read_null = null, $read_null = null);
if ($ready == 0){
continue;
}
echo "$ready events\n";
print_r($read);
// if a new connection is being made add it to the client array
if (in_array($master_socket, $read)){
if (count($clients) <= $max_clients){
echo "accept client...\n";
$clients[] = socket_accept($master_socket);
}else{
echo "max clients reached...\n";
}
// remove master socket from the read array
$key = array_search($master_socket, $read);
unset($read[$key]);
}
echo "client list:\n";
print_r($clients);
// If a client is trying to write - handle it now
foreach($read as $client){
$input = socket_read($client, 1024);
// Zero length string meaning disconnected
if ($input == null) {
$key = array_search($client, $clients);
unset($clients[$key]);
}
$n = trim($input);
if ($input) {
socket_write($client, $input);
}
}
} // eo master loop
// Close the master sockets
socket_close($master_socket);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment