开发者

Why does socket read does not leave loop?

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

开发者_StackOverflow社区
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 != "");
        }

}


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.


i solved it using another method. By my server sending a (" ") statement to the client after all the data has been sent.

Client side will then exit that loop upon receiving the statement.

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);
                if($line != " ")
                echo $line. "\n";
            }
            while($line != " ");
        }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜