Timeout a while loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
agravayne
Forum Newbie
Posts: 8
Joined: Thu Dec 04, 2008 4:55 am

Timeout a while loop

Post by agravayne »

Hello All,

I have a while loop that reads data from a socket until it reaches a specified teminator. This works but I need to be able to time this out so that if the terminator is for some reason omitted then the while loop won't wait forever. I have tried adding a incremental counter but this only ever gets up to one - whether it reads or not.

Here is my code.

Code: Select all

while(substr($clients[$i]['Data'], strlen($clients[$i]['Data'])-4, 4)!="TS:\n")
{
   if(false!== ($data = socket_recv($tempsock, $buf,10240,0)));
   {$clients[$i]['Data'].=$buf;}
}
Any ideas
Thanks
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Timeout a while loop

Post by AbraCadaver »

First off you're not incrementing the $i counter. Secondly, you're checking the value of the variable $clients[$i]['Data'] before it's been defined. Thirdly, why not check that you received data? You'll only get false if there was an error. Not tested but try this:

Code: Select all

// assumes that $i has been defined already and its not a counter in this loop
 
while(($data = socket_recv($tempsock, $buf, 10240, 0)) > 0) {
    if(substr($buf, strlen($buf) - 4, 4) != "TS:\n") {
        $clients[$i]['Data'] .= $buf;
    } else {
        break;
    }
}
-Shawn
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply