9.4. Echo Server

The Echo Server lets you telnet to it and echos back every word you type just
like the Simple Echo Serever but once connected you have 5 seconds between 
every two line you type or it prints Timeout and closes the connection. 
Prints a message both to the client and the console (STDERR) of the server.

Example 9-5. examples/server/echo_server.pl

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

use lib 'lib';
use EchoServer;

EchoServer->run(port => 8000);

Example 9-6. examples/server/lib/EchoServer.pm

package EchoServer;
use warnings;
use strict;

use base 'Net::Server';
use English qw( -no_match_vars ) ;

my $timeout = 5; # give the user 5 seconds to type a line
my $EOL   = "\r\n";

sub process_request {
    my $self = shift;
    eval {

        local $SIG{ALRM} = sub { die "Timeout\n" };

        alarm($timeout);
        while( my $line = <STDIN> ) {
            alarm($timeout);
            $line =~ s/\r?\n$//;
            print qq(You said "$line"$EOL);
            last if $line eq "bye";
        }
    };
    alarm(0);

    
    if ( $EVAL_ERROR ) {
        if ( $EVAL_ERROR eq "Timeout\n" ) {
            print "Timed Out. Disconnecting...$EOL";
            print STDERR "Client timed Out.\n";
        } else {
            print "Unknown internal error. Disconnecting...$EOL";
            print STDERR "Unknown internal error: $EVAL_ERROR\n";
        }
    } else {
        print STDERR "User said bye\n";
    }
    return;
}



1;

If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed