in reply to Re^4: Parsing protocol data: unpack and bytes
in thread Parsing protocol data: unpack and bytes

It turned out that this is not the case. The 'name' and 'clan' fields are max 32 chars, not fixed at 32 chars.

Then your struct definition is wrong.

If the strings are variable length, then use 'Z*':

print for unpack 'n N Z* C Z* C', "\x01\x01\x04\x03\x02\x01The first string\0\xffThe second string\0 +\xff";; 257 67305985 The first string 255 The second string 255
That's why I structured the code a bit more than I usually tend to in perl...

I'm not suggesting you stop structuring your code, just structure is differently. Java streams are just one possible abstraction of the problem.

I would suggest a different abstraction that uses the power of unpack format strings. Have a different class for each packet and pass the buffer into the constructor and have it remove its stuff from that buffer.

package This::Packet; sub new { my( $class, $bufRef ) = @_; my( $ping, $rate, $name, $ctpos, $clantag, $isbot ) = unpack 'n N Z* C Z* C', $$bufRef; my $nPacket = 2 + 4 + length( $name )+ 1 + 1 ## string + null + ctpos + length( $clantag ) + 1 + 1; ## string + null + IsBot # ... validate substr( $$bufRef, 0, $nPacket, '' ); ## remove this packet from th +e buffer return bless { ping => $ping, rate => $rate, name => $name, cpos => $ctpos, clantag => $clantag, isBot => $isBot, }, $class; } ## accessors go here

This way moves all the packets specific information inside a class that deals with that packet. Each class removes it's data from the buffer and the higher level only has to decide which packet to deal with next.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."