# 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.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__
####
$ perl client.pl localhost
Reached 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'
}
];