AnyEvent recursive blocking wait with Plack
Dirk Koopman
djk at tobit.co.uk
Thu Mar 8 15:46:26 CET 2012
On 08/03/12 14:02, Marc Lehmann wrote:
>>> Well, if the Anyevent::HTTPD handler is the only one allowing that then
>>> you are in trouble. If it's a standard feature supported everywehre,
>>> then enjoy - if it's not documented well, you could always ask the Plack
>>> author.
>>
>> Why not use one of the many Plack (http://plackperl.org) compatible
>> frameworks such as: Mojolicious (http://mojolicious.org) or Dancer
>> (http://perldancer.org)? Both of these frameworks (for instance)
>> allow web apps to query other web servers.
>
> Isn't that exactly what he is using? He tried to use AnyEvent::HTTPD,
> which to me looks as plack-compatible as the frameworks you mentioned, and
> also allow web apps to query other web servers.
>
I shouldn't bite - really...
> Do I miss something obvious?
>
Don't use AnyEvent::HTTPD or Plack....
From the Mojolicious::CookBook (lots of good ideas):
Event loops
Internally the Mojo::IOLoop reactor can use multiple event loop
backends, EV for example will be automatically used if installed. Which
in turn allows AnyEvent to just work.
use Mojolicious::Lite;
use EV;
use AnyEvent;
# Wait 3 seconds before rendering a response
get '/' => sub {
my $self = shift;
my $w;
$w = AE::timer 3, 0, sub {
$self->render(text => 'Delayed by 3 seconds!');
undef $w;
};
};
app->start;
Who actually controls the event loop backend is not important.
use Mojo::UserAgent;
use EV;
use AnyEvent;
# Search Twitter for "perl"
my $cv = AE::cv;
my $ua = Mojo::UserAgent->new;
$ua->get('http://search.twitter.com/search.json?q=perl' => sub {
my ($ua, $tx) = @_;
$cv->send($tx->res->json->{results}->[0]->{text});
});
say $cv->recv;
You could for example just embed the built-in web server into an
AnyEvent application.
use Mojolicious::Lite;
use Mojo::Server::Daemon;
use EV;
use AnyEvent;
# Normal action
get '/' => {text => 'Hello World!'};
# Connect application with web server and start accepting connections
my $daemon =
Mojo::Server::Daemon->new(app => app, listen => ['http://*:8080']);
$daemon->start;
# Let AnyEvent take control
AE::cv->recv;
Helpful?
For what it is worth, I have only used Mojo on some toy apps. I am just
about to do something a bit more interesting by building a Mojo /
AnyEvent web app to directly control a (Davis Vantage Pro II) weather
station (via its serial port), outputting decent HTML5 /
websocket->javascript style output. None of the native weather programs
out there are very good. They all seem to have been written 15 years
ago, or in a style that is that old, and there seem to be no decent perl
web based solutions.
Dirk
More information about the anyevent
mailing list