Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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


Comment on Re: Creating A Single Threaded Server with AnyEvent
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1002611]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (9)
As of 2014-09-02 21:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (29 votes), past polls