Created
October 31, 2011 14:57
-
-
Save zigorou/1327666 to your computer and use it in GitHub Desktop.
echo servers by AnyEvent
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 AnyEvent; | |
| use AnyEvent::Handle; | |
| use AnyEvent::Socket; | |
| use Data::Dump qw(dump); | |
| tcp_server(undef, 50000, sub { | |
| my ($conn, $host, $port) = @_; | |
| AE::log(info => "New connection ($host:$port)"); | |
| my $hdl; | |
| $hdl = AnyEvent::Handle->new( | |
| fh => $conn, | |
| on_read => sub { | |
| # my $hdl = shift; | |
| $hdl->push_read( | |
| line => sub { | |
| my ($hdl, $line) = @_; | |
| AE::log(debug => "input: $line ($host:$port)"); | |
| $hdl->push_write($line . "\n"); | |
| } | |
| ); | |
| }, | |
| on_eof => sub { | |
| AE::log(info => "Connection closed by peer ($host:$port)"); | |
| undef; | |
| }, | |
| ); | |
| }); | |
| AE::log(info => "Listening port 50000 (pid: $$)"); | |
| AnyEvent->condvar->recv; |
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 AnyEvent; | |
| use AnyEvent::Socket; | |
| use Data::Dump qw(dump); | |
| tcp_server(undef, 50000, sub { | |
| my ($conn, $host, $port) = @_; | |
| AE::log(info => "New connection ($host:$port)"); | |
| my $poll_watcher; | |
| $poll_watcher = AnyEvent->io( | |
| fh => $conn, | |
| poll => "r", | |
| cb => sub { | |
| my $len = sysread($conn, my $buffer, 1024); | |
| AE::log(debug => $len); | |
| unless (defined $len) { | |
| AE::log(warn => $!); | |
| undef $poll_watcher; | |
| } | |
| elsif ($len == 0) { | |
| AE::log(info => "Connection closed by peer ($host:$port)"); | |
| undef $poll_watcher; | |
| } | |
| else { | |
| AE::log(debug => $buffer); | |
| syswrite($conn, $buffer, $len); | |
| } | |
| } | |
| ); | |
| }); | |
| AE::log(info => "Listening port 50000 (pid: $$)"); | |
| AnyEvent->condvar->recv; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment