Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 5000
and type something.
// Based on
// Set the ip and port we will listen on
$address = '';
$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
// 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){
echo "$ready events\n";
// 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);
echo "max clients reached...\n";
// remove master socket from the read array
$key = array_search($master_socket, $read);
echo "client list:\n";
// 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);
$n = trim($input);
if ($input) {
socket_write($client, $input);
} // eo master loop
// Close the master sockets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.