1
votes

I work on a personal project and i have a problem for managing socket on a multi client server.

So, according to php.net, it's possible to put in argument of socket_read() a socket create by socket_create or accepted by socket_accept...

If i understand, socket create by socket_create is a "local" socket and sockets send by socket_accept are sockets client, it's that ?

in this case, i would like to put my server socket in parameter of socket_read for wait a client among several write on this socket.

more clearly, i accept 4 clients and wait that one of them write on this socket, but i can't put in parameter a specific client socket because i don't know which of them will write...

And when i put the socket create by : socket_create, php return me an error

my native language is not English as you could see, but nobody could answer me...

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
            echo "socket_create() a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
        } 

        if (socket_bind($sock, $this->address, $this->port) === false) {
            echo "socket_bind() a échoué : raison : " . socket_strerror(socket_last_error($sock)) . "\n";
        }

        if (socket_listen($sock, 5) === false) {
            echo "socket_listen() a échoué : raison : " . socket_strerror(socket_last_error($sock)) . "\n";
        }

        for($i=0;$i<$this->maxClient;$i++){

            if(($client = socket_accept($sock)) === false){
                 echo "socket_accept() a échoué : raison : " . socket_strerror(socket_last_error($sock)) . "\n";
                 break; 
            }else echo "<br/>Client $client[$i] has connected\n";


            $this->joueurs[$i] = new Joueur($client,$i);
        } 
                    while($start){
            $messageClient = socket_read($sock , 1024);
                        ......
                    }

So,I have two problems, the first is, i need that socket_read() doesn't block my script and Scanning my sockets until it find something to read.

The second problem is that as my program does it not stopped, my client don't receive anything and when i stop my serveur my client receive the message...

Have you any idea ?

Thanks

2
socket_create by definition always creates "local" sockets - you cannot reach out to another machine and create a socket there via socket_create. - Marc B

2 Answers

0
votes

Get familiar with socket_select - it allows for waiting on multiple sockets to become readable or/and writable, or have errors. A listening socket becomes readable when there's new connection pending/ready to be accept()-ed.

0
votes

i found my problem : for unlock socket_read()

socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>1, "usec"=>0));
                socket_set_nonblock($socket);

And for clear buffer i use "/n" without that i could receive message in my client only when the server stop.