Jump to content

stream timeout during blocking read


RoyHB

Recommended Posts

I connect to a server using fsockopen, then read lines of ASCII from the server forever or until feof().

The server either sends data or else if no data available it sends a keep alive string every 30 seconds or so.

 

I'm using a blocking read (fgets().

I'd like to have a timeout occur is nothing is received by the fgets() in n seconds.  Presumably if no data and no blank record then the connection has failed and I can try to reconnect.

 

How can I get the fgets read to time out after some number of seconds if nothing is received? (or should I be using some other sort of read?)

 

error_reporting(E_ERROR | E_PARSE | E_NOTICE);
while (true) {
    $connected = FALSE;
    while ( ! $connected) {
             $handle = fsockopen("server.someplace.com",21798,$sockErrno,$sockErrStr);
             if (! $handle) {
                echo "Not connected yet, errno = ".$sockErrno.":".$sockErrStr."".PHP_EOL;
                $sleepTime = 30;
                while ($sleepTime > 0) {
                    echo " Sleeping: ".$sleepTime. " seconds ".chr(13);
                    sleep(1);
                    $sleepTime --;
                } // while sleeptime		
            } // ! connected
           else $connected = TRUE;
    }
    // Now connected - alert the console and process reads
    echo chr(7);sleep(1);echo chr(7);sleep(1);echo chr(7);
    $fileName = "/localDir/localFile/data.txt";
    $fh = fopen($fileName,"a");
    fwrite($fh,"Connection established at ". date("m-d H:i:s") . PHP_EOL);
    while ( ! feof($handle)) {
          $a="";
          $a = fgets($handle,256);
          if (strlen($a) == 0) {
              echo "Received keepalive packet".PHP_EOL;
          }
          else {
              echo "Received: " . $a . " Length of received buffer = ". strlen($a) . PHP_EOL;
              fwrite($fh,$a);
          }
     }
     fclose($fh);
}

Link to comment
https://forums.phpfreaks.com/topic/243154-stream-timeout-during-blocking-read/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.