Created
June 1, 2018 03:06
-
-
Save userid/662c7bef1bc15fc0d0ba5cfd8f7edf95 to your computer and use it in GitHub Desktop.
A simple TCP server written in Perl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment