in reply to Send an Array of Hash in Socket

I'd use a text-based format for data interchange, such as JSON. Read The Importance of Being Textual (The Art of Unix Programming, by Eric Steven Raymond, 2003) for a rationale.

Server code:

# server.pl use strict; use warnings; use Data::Dumper; use JSON::XS; use IO::Socket; use Sys::Hostname; use constant BUFSIZE => 1024; my $JSONObject = JSON::XS->new->ascii->pretty->allow_nonref(); my $host = hostname; my $port = shift || '10280'; my $socket = new IO::Socket( Domain => PF_INET, Proto => getprotobyname('tcp'), LocalAddr => $host, LocalPort => $port, Listen => 1, #SOMAXCONN, #ReuseAddr => SO_REUSEADDR, ) or die $@; my $buffer; print "Waiting to do service...\n"; while (my $client = $socket->accept) { print "Client: ", $client->peerhost, " Connected..\n"; syswrite($client, "Reached Server\n", BUFSIZE); if (sysread($client, $buffer, BUFSIZE) > 0) { my @AoH = $JSONObject->decode($buffer); print "AoH: " . Dumper(@AoH); } } __END__
Client code:
# client.pl use strict; use warnings; use JSON::XS; use IO::Socket; use constant BUFSIZE => 1024; my $JSONObject = JSON::XS->new->ascii->pretty->allow_nonref(); my @AoH = ( { husband => "barney", wife => "betty", son => "bamm bamm", }, { husband => "george", wife => "jane", son => "elroy", }, { husband => "homer", wife => "marge", son => "bart", }, ); my $host = shift or die "Usage: client.pl host [port]\n"; my $port = shift || '10280'; my $socket = new IO::Socket( Domain => PF_INET, PeerAddr => $host, PeerPort => $port, Proto => getprotobyname('tcp'), Timeout => 60, ) or die $@; my $buffer; if (sysread($socket, $buffer, BUFSIZE) > 0) { syswrite(STDOUT, $buffer); } syswrite($socket, $JSONObject->encode(\@AoH), BUFSIZE); close($socket); __END__
Running the client:
$ perl client.pl localhost Reached Server
Running the server:
$ perl server.pl Waiting to do service... Client: 127.0.0.1 Connected.. AoH: $VAR1 = [ { 'son' => 'bamm bamm', 'wife' => 'betty', 'husband' => 'barney' }, { 'son' => 'elroy', 'wife' => 'jane', 'husband' => 'george' }, { 'son' => 'bart', 'wife' => 'marge', 'husband' => 'homer' } ];
--
No matter how great and destructive your problems may seem now, remember, you've probably only seen the tip of them. [1]