Yemto
Yemto

Reputation: 613

socket_select never time out

I have been trying to make a PHP socket server, something I never done before. So I might not get how all the socket_* functions work.

What I have trouble with is the timeout function in socket_select.

while(true){
    //Copy $clients so the list doesn't get modified by socket_select();
    $read = $clients;
    $write = $clients;

    //new socket tries to connect
    if(!$new = socket_accept($socket)){
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error()); break;
    }

    //Accept the new client
    if(!in_array($new, $clients)){
        $clients[] = $new;
        sendMessage($new, "Hello and welcome to the PHP server!");
    }

    //Wait for read
    socket_select($read, $write, $empty, 5, 5);

    foreach($read as $client){
        $id = array_search($client,$clients);
        echo $id." ".readMessage($client);
    }

    //Write data to the connected sockets
    foreach($write as $client){
        sendMessage($client, rand(0,99999));
    }

    echo "I'm bored\n"; 
}

From what I understand of socket_select is that this script should say, "I'm bored" every 5 seconds. But it doesn't, why?

Why I want to timeout socket_select is to make a loop so I can send data to the connected sockets.

Upvotes: 0

Views: 490

Answers (1)

user149341
user149341

Reputation:

You're calling socket_accept() every time around the loop. This call will block if no new connections have arrived.

Add $socket to the array of sockets you pass to socket_select(), and only call socket_accept() if that socket shows up as readable. (You'll also need to make that socket an exception in your other loops so that you don't try to write to it.)

Upvotes: 1

Related Questions