Hello dear Monks,

I tried reading from a socket as one might from a file (I know, no error handling, that's not the point here):

my $buf; my $read; while(($read = $s->read( $buf, 1024 )) > 0) { my $chunk = substr $buf, $read; # process chunk }
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?

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.


In reply to read from socket blocks until buffer is full by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.