Is it possible to have multiple connections on a single socket?

0

The following code allows only one client and not several at the same time. Is it possible to create something, leave multiple clients connected?

$socket = socket_create( AF_INET , SOCK_STREAM , SOL_TCP );

socket_bind( $socket , 'localhost' , '2000' );

socket_listen( $socket );

while ( true ) {
  $client = socket_accept( $socket );
  socket_write( $client , 'Aê! Seja bem-vindo!' );
}
    
asked by anonymous 27.04.2018 / 01:59

1 answer

1

Yes, one of the possible ways is with the function socket_select

link

(I recommend using php's English documentation for socket, since Portuguese has almost nothing)

Below an example

...
$clientes = array($socket);

//para o socket_select
$write = null;
$except = null;

while (true)
{
    $read = $clientes;

    if (socket_select($read, $write, $except, 0) < 1)
        continue;

    if (in_array($socket, $read))
    {
        $novo_cliente = socket_accept($socket);

        socket_write( $novo_cliente , 'Aê! Seja bem-vindo!' );

        //adiciona essa nova conexão ao array $clientes
        $clientes[] = $novo_cliente;
    }
}

Hugs

    
27.04.2018 / 04:23