Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Using IO::Socket::INET in a server context, I've been playing with how to read from a connected client. The client sends binary data of different 'types' (type 1 is one format that is variable in length, type 2 another, but predictable in length). There's an indicator near the beginning of the record that gives an idea of the record type followed by a couple of bytes telling how big the overall length is and a flag.
I thought I could get away with reading the first bytes of the header to determine the type, and then read some more afterward, like so:
## Byte 1 - type
## Byte 2 - y, flag
## Byte 3 - x, 8 + 12 * byte 4
## Byte 4 - entry count
while ( <$client> ) {
$client->read($raw_header, 6);
$junk = unpack('H2', $raw_header);
if ($junk eq "01") {
print "Variable length is coming!\n";
$more = unpack('H6', $raw_header);
print "Three byte header is: $more\n";
## Flag byte, noted but not used
$y = substr( $more, 2, 2 );
## Length of data calculated as 8 bytes + 12 * $ec
$x = substr( $more, 4, 2 );
print "X, the variable record length is: $x\n";
print "Y, the flag is: $y\n";
## Read the entry count byte
$client->read($raw_header, 2);
$ec = unpack('H2', $raw_header);
print "Sub-record Entry Count is: $ec\n";
}
I was under the impression that I could do a second read() to get the following entry count byte so I could calculate the length and read() the rest of the data correctly... but I know from tcpdump output on the wire that the number $ec gets isn't the one I'm seeing from tcpdump
(A previous version of the code above had me pulling just one more byte and confirmed I was getting the right number for the entry count, but the question about this code segment above stands.)
I was under the impression I could read some bytes, then do something and read some more from where I left off, etc. Looks like I can't, so how would this be properly done?
Thanks,
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: reading from a socket, a little at a time
by Anonyrnous Monk (Hermit) on Feb 15, 2011 at 19:06 UTC | |
by Anonymous Monk on Feb 15, 2011 at 19:37 UTC | |
|
Re: reading from a socket, a little at a time
by Anonyrnous Monk (Hermit) on Feb 15, 2011 at 21:20 UTC | |
by Anonymous Monk on Feb 19, 2011 at 21:03 UTC |