use strict;
use IO::Socket;
use threads;
use warnings;
print "Enter port: ";
chomp(my $port = <STDIN>);
my $socket = new IO::Socket::INET (
LocalHost => 'localhost',
LocalPort => $port,
Proto => 'tcp',
Reuse => 1,
Listen => 5,
)
or die "Error $!\n";
print "Server $0 is now active.\n";
while (1) {
my $new_client = $socket->accept();
threads->new(\&client_sub, $new_client);
}
sub client_sub {
my ($client) = @_;
my $buffer = undef;
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
alarm 4;
chomp(my $first = <$client>);
print $first;
chomp(my $second = <$client>);
print $second;
alarm 0;
# some text processing, final string ends in $_
print $client $_;
};
if ($@) {
print $client "Timeout.\n" if $@ eq "alarm\n";
} else {
die "DIED $!\n";
}
close $client;
}