simple tcp server

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;

use IO::Socket::INET;
use AnyEvent;
use AnyEvent::Util;
$AnyEvent::Util::MAX_FORKS = 15;

my $handled = 0;
$|++;

my $server = IO::Socket::INET->new(
‘Proto’ => ‘tcp’,
‘LocalAddr’ => ‘localhost’,
‘LocalPort’ => 1234,
‘Listen’ => SOMAXCONN,
‘Reuse’ => 1,
) or die “can’t setup server: $!\n”;
print “Listening on localhost:1234\n”;

my $cv = AnyEvent->condvar;
my $w; $w = AnyEvent->io(
fh => \*{ $server },
poll => ‘r’,
cb => sub {
$handled++;
$cv->begin;
fork_call \&handle_connections,
$server->accept,
sub {
my ($client) = @_ ;
print ” – Client $client closed\n”
}
}
);
$cv->recv;

#
# Subroutines
#
sub handle_connections {
my ($client) = @_;

my $host = $client->peerhost;
print “[Accepted connection from $host]\n”;

print $client “Hi, you’re client #$handled\n”;
chomp ( my $input = <$client> );
my $output = reverse $input;
print $client $output, “\n”;
print $client “Bye, bye.\n”;

$cv->end;
return $host;
}

Leave a Reply

Your email address will not be published. Required fields are marked *