Skip to content

Instantly share code, notes, and snippets.

@ggl
Last active December 19, 2015 18:59
Show Gist options
  • Save ggl/6002766 to your computer and use it in GitHub Desktop.
Save ggl/6002766 to your computer and use it in GitHub Desktop.
Echo server example using AnyEvent
#!/usr/bin/env perl
use strict;
use warnings;
use AnyEvent;
use AnyEvent::Socket;
use AnyEvent::Handle;
my ($host, $port) = parse_hostport('127.0.0.1:8000');
my %conn;
tcp_server $host, $port, sub {
my ($fh, $host, $port) = @_
or die "Cannot bind to $host:$port: $!";
my $hdl; $hdl = AnyEvent::Handle->new(
fh => $fh,
on_read => sub {
shift->push_read( line => sub {
my ($hdl, $ln) = @_;
my $client = $conn{fileno($fh)};
if ($ln) {
if ($ln eq '.') {
my $client = delete $conn{fileno($fh)};
$hdl->destroy;
warn "done\n";
}
else {
$hdl->push_write("$ln\n");
}
}
}
);
},
on_eof => sub {
my $hdl = shift;
my $client = delete $conn{fileno($fh)};
$hdl->destroy();
warn "done\n";
},
on_error => sub {
my ($hdl, $fatal, $msg) = @_;
my $client = delete $conn{fileno($fh)};
warn "error\n";
$hdl->destroy();
}
);
$conn{fileno($fh)} = $hdl;
$hdl->push_write("hello there\n");
};
print "Listening on $host:$port\n";
AE::cv->wait;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment