0

I am creating a socket in this way:

$fp = fsockopen("tcp://".$ip, $port, $errno, $errstr);
stream_set_timeout($fp, 1); // timeout is one second
stream_set_blocking($fp, 1); // block until data is available

However, when I read I always get a timeout, even after reading data:

while(true) {
    $result = fgets($fp, 4096);                 
    if(empty($result)) {
        break;
    }
    else {              
        echo $result;
    }
}

I think my method of reading is wrong because I don't fully understand how php sockets work in the background. My intent is to read until there's no more data, or give up if I've tried to read data for a certain amount of time but no data has become available.

In various PHP socket examples I've seen the use of a while(!feof($fp)) to stop a read loop, but as far as I'm concerned the other end will never send an eof marker. They only send newline delimited messages.

Any ideas?

Thanks.

Gabe
  • 51
  • 3
  • 2
    Doesn't this help? http://stackoverflow.com/questions/149860/how-to-prevent-fgets-blocks-when-file-stream-has-no-new-data Possible duplicate – Salomao Rodrigues Dec 19 '15 at 00:38
  • 1
    If it doesn't have a new message to send, you'll time out. Isn't that what you expect? – Barmar Dec 19 '15 at 01:17
  • You explicitly set it to "blocking" so your `fgets` blocks **unless** one of the following is true: a `newline` or `EOF` is read or 4095 bytes have been read. So it looks like your endpoint is sending a message shorter than 4K and doesn't terminate it with a newline, yet still keeping the connection open. In this case your 1s timeout triggers. – ccKep Dec 19 '15 at 02:20

0 Answers0