Page 1 of 1

Timeout a while loop

Posted: Thu Nov 05, 2009 6:39 am
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

Re: Timeout a while loop

Posted: Thu Nov 05, 2009 8:55 am
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