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

Asked

Viewed 180 times

0

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

$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!' );
}

1 answer

1

Yes, one of the possible ways is with socket_select

http://php.net/manual/en/function.socket-select.php

(recommend using php’s English documentation for socket, as the Portuguese version 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.