in reply to IO:Socket::INET - how to receive binary data

Your problem is that you're using <> to read line by line:
my $answer = <$remote> || '---';

Since your header can contain (multiple!) \n characters, you can't use <> to get it (you may be able to use <> for the data, depending on whether it has embedded \n characters). Instead of using <>, you want to use read or recv to get first the header, then the remaining bytes. You can forget about the linefeed, since you have a count:

my $header; $remote->read($header, 8); ($op, $hvers, undef, undef, $count) = unpack "C4N", $header; my $data; $remote->read($data, $count);

If you want to mix the read idioms (per tye's suggestion) (of course, this assumes you can't have embedded \n in your data), you can do it this way:

my $header; $remote->read($header, 8); ($op, $hvers, undef, undef, $count) = unpack "C4N", $header; my $data = <$remote>;

update: changed to mention read and show mixture of idioms (thanks tye!), attribute to tye correctly

Replies are listed 'Best First'.
Re: Re: IO:Socket::INET - how to receive binary data
by Aighearach (Initiate) on Jun 24, 2001 at 06:39 UTC
    You can also just do a sysread() for binary data, if you're not going to mix it with buffered reads/writes. I would add a test for the linefeed afterwards, to detect the case where the connection drops in the middle.
    --
    Snazzy tagline here

      I prefer to use read over sysread and recv because it works with buffered I/O operations while the other two don't. Though if you are using UDP in certain ways, then you might want to use recv so you can get the source address for each packet. In rare cases, the "flags" argument to recv can also come in handy so that you can MSG_PEEK at the data without reading it or check for out-of-band data.

              - tye (but my friends call me "Tye")
Re: Re: IO:Socket::INET - how to receive binary data
by Rudif (Hermit) on Jun 25, 2001 at 03:23 UTC
    Thank you bikeNomad.

    I adopted your first solution and it works neatly. Also your logic matches neatly the protocol.

    I ought to try alternatives suggested by other monks and get the understanding of tradeoffs.

    Rudif