AnyEvent with Coro, AKA async TCP daemon.

Darin McBride darin.mcbride at shaw.ca
Thu Aug 1 19:31:07 CEST 2013


On Thursday August 1 2013 4:57:59 PM Antti Linno wrote:
> Good day.
> 
> I'm trying to build a simple non-blocking TCP daemon. If I need HTTP
> daemon, should I use Twiggy?

I've been using AnyEvent::HTTPD, but many options could work.

> This is what I have so far:
> 
> use Modern::Perl '2012';
> use EV;
> use AnyEvent::Socket;
> use Coro;
> 
> sub start_thread($$$$) {
>      my ( $time, $fh, $host, $port ) = @_;
>      return async {
>          say "Starting sleep of $time, $host, $port";
>          sleep $time;

No sleeping.

Use Coro::AnyEvent::sleep instead.

>          say "Done sleeping!";
>      };
> }
> 
> AnyEvent::Socket::tcp_server undef, 11211, sub {
>    my ( $fh, $host, $port ) = @_;
> 
>    start_thread 20, $fh, $host, $port;
>    }, sub {
>    my ( $fh, $thishost, $thisport ) = @_;
>    AE::log info => "Bound to $thishost, port $thisport.";
>    };
> 
> EV::loop;
> 
> The problem is, this solution is blocking. If I make two requests, then
> the second one is pending, while the first one sleeps.

You do have to ensure you don't block.  And sleep is one documented to do so.

Presumably, you're not really sleeping, you're doing this just to look at 
things.  If you are just testing, use Coro::AnyEvent::sleep, and keep going.  
If you're replicating a problem from a bigger app, you'll have to find out 
what is actually blocking as presumably you're not actually sleeping in a 
server.  You may be calling system, for example (use AnyEvent::Util::run_cmd 
instead).  But whatever it is, you have to basically find that and make it 
asynchronous/non-blocking.



More information about the anyevent mailing list