Permalink
Browse files

Add stupid http_get for async HTTP requests

  • Loading branch information...
1 parent 4d26dab commit 8e536b80bce8cdd845ceda19b1913e74f9f5724c @tadzik committed Nov 26, 2012
Showing with 72 additions and 0 deletions.
  1. +51 −0 http-test.pl
  2. +21 −0 lib/MuEvent.pm
View
@@ -0,0 +1,51 @@
+use MuEvent;
+
+my @urls = <
+ duckduckgo.com
+ cpan.org
+ kosciol-spaghetti.pl
+ perlcabal.org
+ perl6.org
+>;
+my $count = @urls.elems;
+my $starttime;
+
+sub http_get_eager(:$url!) is export {
+ my $sock = IO::Socket::INET.new(host => $url, port => 80);
+ my $req = "GET / HTTP/1.1\r\n"
+ ~ "Connection: Close\r\n"
+ ~ "Host: $url\r\n"
+ ~ "User-Agent: MuEvent/0.0 Perl6/$*PERL<compiler><ver>\r\n"
+ ~ "\r\n";
+ $sock.send($req);
+ $sock.recv;
+ $sock.close;
+}
+
+say "=== BLOCKING FETCHING ===";
+my $last;
+$starttime = $last = now;
+for @urls -> $url {
+ http_get_eager(url => $url);
+ say sprintf "%-25s has loaded in %s", $url, now - $last;
+ $last = now;
+}
+say "Finished in {now - $starttime} seconds";
+
+
+sub handler ($what, $content) {
+ say sprintf "%-25s has loaded in %s", $what, now - $starttime;
+ unless --$count {
+ say "Finished in {now - $starttime} seconds";
+ exit 0;
+ }
+}
+
+say "=== NON-BLOCKING FETCHING ===";
+$starttime = now;
+
+for @urls -> $url {
+ http_get(url => $url, cb => sub { handler($url, $^content) })
+}
+
+MuEvent::run;
View
@@ -23,6 +23,27 @@ class MuEvent::Condvar {
}
}
+sub http_get(:$url!, :&cb!) is export {
+ my $sock = IO::Socket::INET.new(host => $url, port => 80);
+ my $req = "GET / HTTP/1.1\r\n"
+ ~ "Connection: Close\r\n"
+ ~ "Host: $url\r\n"
+ ~ "User-Agent: MuEvent/0.0 Perl6/$*PERL<compiler><ver>\r\n"
+ ~ "\r\n";
+ my $callback = sub {
+ &cb($sock.recv);
+ $sock.close;
+ }
+
+ MuEvent::socket(
+ socket => $sock,
+ poll => 'r',
+ cb => $callback,
+ );
+
+ $sock.send($req);
+}
+
#= Add an event run after a certain amount of time
our sub timer(:&cb!, :$after!, :$interval, :%params) {
@timers.push: {

0 comments on commit 8e536b8

Please sign in to comment.