Re: fread() behaviour

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 20 Nov 2008, at 01:29, Rene Fournier wrote:
I'm trying to understand something about fread(). I'm using fread() on an incoming socket stream that will send, for example, 26630 characters:

while ( ($buf=fread($read[$i], 8192)) != '' ) {
	$sock_data .= $buf;
	usleep(1000);
	echo ".";
	}
echo ",";


As soon as the socket client sends the data, immediately the server will echo:

................................................................................................................................................

Then wait nearly a minute, and echo:

,

So my question is, why does fread wait if there is nothing more to read? Shouldn't it return immediately? (That's what I want.) And as for the delay, it's there so that if the incoming data is a little slow, it has time to catch up with fread. Thanks.

As Craige already mentioned, fread will read bytes until it meets an EOF so unless the other side sends one or closes the socket fread will wait for the number of characters you've asked for (8192) or a timeout (which is the delay you're seeing). In other words it's not detecting the end of the data, it's just timing out waiting for more.

You ideally want to have the other side tell you how many bytes it's going to send. If you can't do that then hopefully the data you're receiving has some sort of structure so you can check the incoming data for some terminating string. If not then you've got a problem that can't be reliably solved. You could mess around with the timeout and/or make use of functions like socket_select to check for waiting data, but what you'll end up with will be problematic on slow connections and generally unreliable.

-Stut

--
http://stut.net/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux