Search code examples
perlanyevent

AnyEvent::HTTP basic example not working


AnyEvent::HTTP

Tried on Debian and Centos, both with perl 5.10

Not a sound after

perl -Mstrict -we 'use AnyEvent::HTTP; http_get "http://www.nethype.de/", sub { print $_[1] }; sleep 20'

Is there something fundamentally broken with module, or do I need more recent perl version, although I would expect complaints about it?

EDIT:

So I need event loop, is there some simple example which would demonstrate AE::HTTP usage?


Solution

  • The problem is that sleep, not being part of AnyEvent, doesn't execute the event loop that permits AnyEvent::HTTP to fetch asynchronously. When you block, you want to block using something AE-aware such as a condition variable.

    This program creates a condition variable called $exit_wait and then makes the HTTP request. The program can continue running while the request is made and the response received.

    Once the program has reached a point where it needs the information from the HTTP request, it calls recv on the condition variable. This allows the callback to trigger when the HTTP request has also completed. All it does is dump the $headers hash.

    In this case I have written it so that the callback also does a send on the condition variable, which causes the program to end its recv call and continue on. Without it the program will be left in an endless wait state.

    I can't help further without knowing more about your application.

    use strict;
    use warnings;
    
    use AnyEvent::HTTP;
    use Data::Dump;
    
    STDOUT->autoflush;
    
    my $exit_wait = AnyEvent->condvar;
    
    my $handle = http_request
      GET => 'http://www.nethype.de/',
      sub {
        my ($body, $headers) = @_;
        dd $headers;
        $exit_wait->send;
      };
    
    # Do stuff here
    
    $exit_wait->recv;