<?php

set_time_limit(0);

define("MAX_CLIENTS", 10);

// the $listener socket doesn't actually serve 
// clients, it only listens for connections and
// hands them off to the $client array below.

$listener = socket_create(AF_INET, SOCK_STREAM, 0);
socket_setopt($listener, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($listener, "0.0.0.0", 10000);
socket_listen($listener);


// $client will hold our clients while they're connected...

$client = array();

while (1)
{
    // these next lines set up our clients and our
    // listener socket for reading...

    $read[0] = $listener;
    for ($i = 0; $i < MAX_CLIENTS; $i++)
    {
        if ($client[$i] != null)
            $read[$i + 1] = $client[$i];
    }

    // now a blocking call to socket_select(). This will
    // wait forever until a connection is received.

    $nready = socket_select($read, $null, $null, null);


    // if a new connection is being made, accept it and
    // put it into the client array...

    if (in_array($listener, $read))
    {
        for ($i = 0; $i < MAX_CLIENTS; $i++)
        {
            if ($client[$i] == null)
            {
                $client[$i] = socket_accept($listener);
                break;
            }
            else if ($i == MAX_CLIENTS - 1)
                trigger_error("too many clients", E_USER_ERROR);
        }

        if (--$nready <= 0)
            continue;
    }


    // if we have clients that are trying to write
    // to the server, handle them now...

    for ($i = 0; $i < MAX_CLIENTS; $i++)
    {
        if (in_array($client[$i], $read))
        {
            $n = trim(socket_read($client[$i], 1024));
            socket_getpeername($client[$i], $host, $port);

            if ($n)
            {
                for ($j = 0; $j < MAX_CLIENTS; $j++)
                {
                    if ($client[$j])
                        socket_write($client[$j], "From $host:$port: $n\n\r");
                }
            }            
            else
            {
                for ($j = 0; $j < MAX_CLIENTS; $j++)
                {
                    if ($client[$j])
                        socket_write($client[$j], "Disconnecting $host:$port\n\r");
                }
                socket_close($client[$i]);
                unset($client[$i]);
            }
        }
    }
}

?>
