Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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]
[GotToBTru]: Like most Swiss Army Knives, you can cut yourself trying to find the blade you actually want
[GotToBTru]: i am satisfied with the default settings turning the seemingly random formatting into something reliable
[Corion]: GotToBTru: Yeah, I started a quick(ly implemented but slowly running) implementation of a program that would guess the "best" configuration (that is, least amount of changes) from my code, but then found that it stops parsing the source as soon as it ..
[GotToBTru]: sadly, it can't do anything about this
[Corion]: ... encounters sub foo($bar,$baz) {, which is something I like nowadays
[Corion]: GotToBTru: Yeah, that stuff is hard to do away automatically ;)
[GotToBTru]: yeah, you mentioned it could not handle signatures

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (11)
As of 2017-02-27 14:35 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (387 votes). Check out past polls.