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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |