http://www.perlmonks.org?node_id=1002611


in reply to Creating A Single Threaded Server with AnyEvent

(a) We prefer cross-posting to be mentioned. It's just polite. (Many people watch both sites, so they don't need to waste time reading both posts.)

(b) You're not getting better answers on stackoverflow, are you sure your doubts are for perlmonks? (IMO, you shouldn't really post where you have doubts anyway, both sites are valid.)

(c) You're blocking inside a callback. That's not allowed. There are a few ways to handle this. My preference is to launch a Coro thread from within the tcp_server callback. But without Coro, something like this might be what you're looking for:

#!/usr/bin/env perl5.16.2 use AnyEvent; use AnyEvent::Handle; use AnyEvent::Socket; my $cv = AE::cv; my $host = '127.0.0.1'; my $port = 44244; my %connections; tcp_server( $host, $port, sub { my ($fh) = @_; print "Connected...\n"; my $handle; $handle = AnyEvent::Handle->new( fh => $fh, poll => 'r', on_read => sub { my ($self) = @_; print "Received: " +. $self->rbuf . "\n"; }, on_eof => sub { my ($hdl) = @_; $hdl->destroy(); }, ); $connections{$handle} = $handle; # keep it alive. return; }); print "Listening on $host\n"; $cv->recv;
Note that I'm only waiting on one condvar. And I'm storing the handles to keep the AnyEvent::Handle objects alive longer. Work to clean up the $self->rbuf is left as an excersise for the reader :-)

Update: cross-posted answer, too