Non-blocking sockets

Instead of waiting for the socket to become readable, it is also possible to continuously poll the socket to see if it has any data. By setting the socket to non-blocking mode with stream_set_blocking, fread() will never block. If there is data available, fread() will return it. If it isn't, fread() will return an empty string.

stream_set_blocking($socket, false);

$stop = microtime(true) + 4;
while (microtime(true) < $stop) 
{
    if (feof($socket))
    {
        break;
    }

    echo fread($socket, 2000);
}

This loop may use a lot of processing power if there is nothing to read. To prevent this, put an usleep() in the loop or combine this method with stream_select(): wait until there is something to read, and then read it in a non-blocking way.