Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I tried reading from a socket as one might from a file (I know, no error handling, that's not the point here):
When the socket is not closed after the sender sent its stuff the read blocks until 1024 bytes are available. So if I don't know in advance how many data I'm about to receive, I have to use a buffer size of one. Is this correct? If yes, isn't this inefficient? If not, how would a better solution look like?my $buf; my $read; while(($read = $s->read( $buf, 1024 )) > 0) { my $chunk = substr $buf, $read; # process chunk }
An example would be parsing an HTTP header. The length field is not always at the same position so until I find it, I have to take small steps in order not to try to read more bytes than are available in the current response. With keep-alive that socket stays open so no EOF there.
The main reason I ask is because I do a lot of Java programming. When you read from a socket in Java the read returns even if not enough data is received to fill the whole buffer in a short amount of time.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: read from socket blocks until buffer is full
by ikegami (Patriarch) on Feb 27, 2011 at 19:47 UTC | |
by Anonymous Monk on Feb 28, 2011 at 18:13 UTC | |
|
Re: read from socket blocks until buffer is full
by Corion (Patriarch) on Feb 27, 2011 at 18:27 UTC |