in reply to How to use pack/unpack data over a network

I'm no networking guru but here's some untested code that just might do the required input processing reliably.
# $sock is open, probably is a IO::Socket of some type my $total_read = 0; my $full_data = ''; my $total; while ( 1 ) { my $read = 0; while ($read < 4) { $read += read($sock,$data,4-$read,$read) # not sure if last arg should have a +1 on it } $total_read += $read; if (! $total) { $total = unpack("N",$data); } elsif ( $total_read >= $total + 4 ) { process(substr($data,0,$total_read-4-$total)); $full_data .= substr($data,0,$total_read-4-$total); last; } else { $full_data .= $data; process($data); other_process($full_data); } } full_process(substr($full_data,0,$total));
And the sender is
# $data has the required data and $sock is an open socket print $sock pack('N',length($data)) . $data . ("\0" x (4-(length($data +)%4)));

Replies are listed 'Best First'.
Re: Re: How to use pack/unpack data over a network
by Fastolfe (Vicar) on Jan 05, 2001 at 19:45 UTC
    On the sender's side we can go ahead and use the Z pack format, since we don't have to try processing it prematurely:
    my $str_len = length($data); $str_len += (4 - $str_len % 4 || 4); print $sock pack("NZ$str_len", length($data), $data);
    I started out thinking this would be a lot cleaner, but as you can see it doesn't look any better. *shrug*