@param int $maxClients
*/
function start()
{
$this->initFD = @socket_create( AF_INET,SOCK_STREAM,0 );
if( !$this->initFD )
die( "patServer: Could not create socket." );
// adress may be reused
socket_setopt( $this->initFD,SOL_SOCKET,SO_REUSEADDR,1 );
// bind the socket
if( !@socket_bind( $this->initFD,$this->domain,$this->port ) )
{
@socket_close( $this->initFD );
die( "patServer: Could not bind socket to ".$this->domain." on port ".$this->port." ( ".$this->getLastSocketError( $this->initFd )." )." );
}
// listen on selected port
if( !@socket_listen( $this->initFD,$this->maxQueue ) )
die( "patServer: Could not listen ( ".$this->getLastSocketError( $this->initFd )." )." );
$this->sendDebugMessage( "Listening on port ".$this->port.". Server started at ".date( "H:i:s",time() ) );
// this allows the shutdown function to check whether the server is already shut down
$GLOBALS["_patServerStatus"] = "running";
// this ensures that the server will be sutdown correctly
register_shutdown_function( array( $this,"shutdown" ) );
if( method_exists( $this,"onStart" ) )
$this->onStart();
$this->serverInfo["started"] = time();
$this->serverInfo["status"] = "running";
while( true )
{
$readFDs = array();
array_push( $readFDs,$this->initFD );
// fetch all clients that are awaiting connections
for( $i = 0; $i < count( $this->clientFD ); $i++ )
if( isset( $this->clientFD[$i] ) )
array_push( $readFDs,$this->clientFD[$i] );
// block and wait for data or new connection
$ready = @socket_select( $readFDs,$this->null,NULL );
if( $ready === false )
{
$this->sendDebugMessage( "socket_select failed." );
$this->shutdown();
}
// check for new connection
if( in_array( $this->initFD,$readFDs ) )
{
$newClient = $this->acceptConnection( $this->initFD );
// check for maximum amount of connections
if( $this->maxClients > 0 )
{
if( $this->clients > $this->maxClients )
{
$this->sendDebugMessage( "Too many connections." );
if( method_exists( $this,"onConnectionRefused" ) )
$this->onConnectionRefused( $newClient );
$this->closeConnection( $newClient );
}
}
if( --$ready <= 0 )
continue;
}
// check all clients for incoming data
for( $i = 0; $i < count( $this->clientFD ); $i++ )
{
if( !isset( $this->clientFD[$i] ) )
continue;
if( in_array( $this->clientFD[$i],$readFDs ) )
{
$data = $this->readFromSocket( $i );
// empty data => connection was closed
if( !$data )
{
$this->sendDebugMessage( "Connection closed by peer" );
$this->closeConnection( $i );
}
else
{
$this->sendDebugMessage( "Received ".trim( $data )." from ".$i );
if( method_exists( $this,"onReceiveData" ) )
$this->onReceiveData( $i,$data );
}
}
}
}
}