Skip to content

Commit

Permalink
Add stupid http_get for async HTTP requests
Browse files Browse the repository at this point in the history
  • Loading branch information
Tadeusz Sośnierz committed Nov 26, 2012
1 parent 4d26dab commit 8e536b8
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
51 changes: 51 additions & 0 deletions http-test.pl
@@ -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;
21 changes: 21 additions & 0 deletions lib/MuEvent.pm
Expand Up @@ -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 #= Add an event run after a certain amount of time
our sub timer(:&cb!, :$after!, :$interval, :%params) { our sub timer(:&cb!, :$after!, :$interval, :%params) {
@timers.push: { @timers.push: {
Expand Down

0 comments on commit 8e536b8

Please sign in to comment.