TCP provides you with a stream of bytes. It's your job to convert that into a stream of messages. To do that, you need to define what constitutes a message. If the messages aren't fixed-length, the transmitted data itself must provide information allowing you to isolate each message.

For example, each message could end with a sentinel value, such as as a newline. If so, you'd use something like the following:

my $buf = ''; for (;;) { my $rv = sysread($sock, $buf, 64*1024, length($buf)); die $! if !defined($rv); last if !$rv; while ($buf =~ s/^([^\n]*\n)//) { process_msg("$1"); } } die("Partial message") if length($buf);

Or you could prefix each message with the length of the message. If so, you'd use something like the following:

my $buf = ''; my $want; for (;;) { my $rv = sysread($sock, $buf, 64*1024, length($buf)); die $! if !defined($rv); last if !$rv; for (;;) { if ($want) { last if length($buf) < $want; process_msg(substr($buf, 0, $want, '')); $want = 0; } else { last if length($buf) < 4; $want = unpack('N', substr($buf, 0, 4, '')); } } } die("Partial message") if $want || length($buf);

In reply to Re: Getting sysread to read the full packet by ikegami
in thread Getting sysread to read the full packet by MediocreGopher

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.