#!/opt/perl/bin/perl use strict; use warnings; use Net::EasyTCP; # Configuration settings our $port = 7716; our $password = 'secret passphrase or whatever'; # Implementation our $cache = []; our $server = new Net::EasyTCP( mode => "server", port => $port, ) || die "ERROR CREATING SERVER: $@\n"; $server->setcallback( data => \&gotdata, connect => \&connected, disconnect => \&disconnected, ) || die "ERROR SETTING CALLBACKS: $@\n"; print "Server starting on port $port\n"; $server->start() || die "ERROR STARTING SERVER: $@\n"; sub gotdata { my $client = shift; my $serial = $client->serial(); my $data = $client->data(); print "Client $serial sent me some data\n"; if (ref($data) ne 'HASH') { print "Client $serial sent bad data\n"; $client->send('DATA') || die "ERROR SENDING TO CLIENT: $@\n"; $client->close() || die "ERROR CLOSING CLIENT: $@\n"; } if ($data->{password} ne $password) { print "Client $serial sent wrong password\n"; $client->send('PWD') || die "ERROR SENDING TO CLIENT: $@\n"; $client->close() || die "ERROR CLOSING CLIENT: $@\n"; } if ($data->{put}) { push @$cache, $data; print "Client $serial sent data to store\n"; $client->send('OK') || die "ERROR SENDING TO CLIENT: $@\n"; $client->close() || die "ERROR CLOSING CLIENT: $@\n"; } elsif (not @$cache) { print "Client $serial requested data, but there is nothing here\n"; $client->send('NODATA') || die "ERROR SENDING TO CLIENT: $@\n"; $client->close() || die "ERROR CLOSING CLIENT: $@\n"; } else { print "Client $serial requested date, sending one record\n"; my $tosend = shift @$cache; $client->send($tosend) || die "ERROR SENDING TO CLIENT: $@\n"; $client->close() || die "ERROR CLOSING CLIENT: $@\n"; } } sub connected { my $client = shift; my $serial = $client->serial(); print "Client $serial just connected\n"; } sub disconnected { my $client = shift; my $serial = $client->serial(); print "Client $serial just disconnected\n"; }