Asynchronous HTTP requests in Perl 6

Inspired by http://oylenshpeegul.typepad.com/blog/2012/03/asynchronicity.html, I decided to tackle asynchronous  HTTP requests in Perl 6 on Rakudo. Allowing this required a bit of hacking on MuEvent, and the changes are far too ugly and hacky to be released, but here’s how it looks:

    use MuEvent;

    my @urls = <
        cpan.org
        kosciol-spaghetti.pl
        perlcabal.org
        duckduckgo.com
        perl6.org
    >;
    my $count = @urls.elems;
    my $starttime;

    sub handler ($what, $content) {
        say sprintf "%-25s has loaded in %s", $what, now - $starttime;
        unless --$count {
            say "Finished in {now - $starttime} seconds";
            exit 0;
        }
    }

    for @urls -> $url {
        http_get(url => $url, cb => sub { handler($url, $^content) })
    }

    $starttime = now;

    MuEvent::run;

The code results in something like this:

    cpan.org                  has loaded in 0.047303409195493
    perlcabal.org             has loaded in 0.0985883954326499
    duckduckgo.com            has loaded in 0.137316369015216
    perl6.org                 has loaded in 0.175586713955562
    kosciol-spaghetti.pl      has loaded in 0.413971411974607
    Finished in 0.465130828044337 seconds

You may notice that the urls are pretty much ordered – that's because my internet connection is probably way faster than MuEvent's event loop :)

For now http_get() is using bare sockets to send HTTP requests, which is, well, Less Than Awesome at least. Once I figure out how to properly tie LWP::Simple to MuEvent I'll hopefully hack out some proper solution to be released for everyone's joy. Stay tuned.

About these ads

One Comment on “Asynchronous HTTP requests in Perl 6”

  1. Looks cool. It will take me a few days of looking at it before I begin to understand. I was trying to come up with a event loop thingy but It looks like you already solved it, and yous is way more capable then what I could have come up with. I’m still trying to understand IO::Socket:INET any tips? I would like to make an UDP Server/Lister.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.