in reply to Re^2: Best technique to code/decode binary data for inter-machine communication?
in thread Best technique to code/decode binary data for inter-machine communication?
As SuicideJunkie suggest, you were probably trying to use line-oriented xfer functions (ie. print and readline ) on a binmoded socket.
My recommendation would be to use pack/unpack & send/recv like this:
$to->send( pack 'n/a*', $binData ); ... $from->recv( my $len, 2 ); $from->recv( my $binData, unpack 'n', $len );
That's good for packets up to 64k in length. Switch to 'N' to handle up to 4GB.
The nice thing about this is that the receiver always knows how much to ask for; and can verify that he got it (length $binData) which avoids the need for delimiters and works just as well with non-blocking sockets if you need to go that way.
I also found that when it comes to transmitting arrays and hashes, using pack/unpack is usually more compact (and therefore faster) than using Storable, because (for example) an integer always required 4 or 8 bytes binary, but for many values it is shorter in ascii:
use Storable qw[ freeze ];; @a = 1..100;; $packed = pack 'n/(n/a*)', @a;; print length $packed;; 394 $ice = freeze \@a;; print length $ice;; 412 @b = unpack 'n/(n/a*)', $packed;; print "@b";; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 +7 28 29 30 31 32 33 34 35 ... %h = 'aaaa'..'aaaz';; $packed = pack 'n/(n/a*)', %h;; print length $packed;; 158 $ice = freeze \%h;; print length $ice;; 202 %h2 = unpack 'n/(n/a*)', $packed;; pp \%h2;; { aaaa => "aaab", aaac => "aaad", aaae => "aaaf", aaag => "aaah", aaai => "aaaj", aaak => "aaal", aaam => "aaan", aaao => "aaap", aaaq => "aaar", aaas => "aaat", aaau => "aaav", aaaw => "aaax", aaay => "aaaz", }
It doesn't always work out smaller, but it is usually faster and platform independent.
Of course, storable wins if your data structures can contain references to others.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Best technique to code/decode binary data for inter-machine communication?
by locked_user sundialsvc4 (Abbot) on Aug 16, 2012 at 01:55 UTC | |
|
Re^4: Best technique to code/decode binary data for inter-machine communication?
by flexvault (Monsignor) on Aug 16, 2012 at 13:13 UTC | |
by BrowserUk (Patriarch) on Aug 16, 2012 at 14:16 UTC | |
by flexvault (Monsignor) on Aug 16, 2012 at 17:38 UTC | |
by BrowserUk (Patriarch) on Aug 16, 2012 at 18:20 UTC |