Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does socket read does not leave loop?

Tags:

php

sockets

I have a socket client that would read data from the server.

However, it does not leave the do..while loop as soon as there are no more data left to read? why is that so? Thanks

while (true)
{
    $data_old=$data;
    $data = file_get_contents("userInput.txt");

        if($data_old != $data)
        {
            socket_write($socket, $data, strlen($data));
            do
            {
                $line =@socket_read($socket,2048);
                echo $line. "\n";
            }
            while($line != "");
        }

}
like image 766
Dayzza Avatar asked Nov 20 '25 09:11

Dayzza


1 Answers

I believe your problem is that the execution never leaves the while (true) loop and not the while($line != "") one, try this:

while (true)
{
    $data_old = $data;
    $data = file_get_contents('userInput.txt');

    if ($data_old != $data)
    {
        socket_write($socket, $data, strlen($data));

        while (true)
        {
            $line = @socket_read($socket, 2048);

            echo $line. "\n";

            if ($line == '')
            {
                break 2;
            }
        }
    }
}

Is the socket is non-blocking you may also want to use socket_select() with a timeout.

like image 116
Alix Axel Avatar answered Nov 22 '25 22:11

Alix Axel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!