Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Creating A Single Threaded Server with AnyEvent

by Tanktalus (Canon)
on Nov 07, 2012 at 00:31 UTC ( #1002611=note: print w/replies, xml ) Need Help??

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 = ''; 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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1002611]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2018-06-22 12:16 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (124 votes). Check out past polls.