AnyEvent
What is a game loop?
# zlatin.lang
#pseudo code
while(1)
{
do_thing1();
do_thing2();
do_thing3();
...
do_thingN();
}Event Loops
require 'eventmachine'
module EchoServer
def post_init
puts "-- someone connected to the echo server!"
end
def receive_data data
send_data ">>>you sent: #{data}"
close_connection if data =~ /quit/i
end
def unbind
puts "-- someone disconnected from the echo server!"
end
end
# Note that this will block current thread.
EventMachine.run {
EventMachine.start_server "127.0.0.1", 8081, EchoServer
}AnyEvent
use AnyEvent::Loop;
use AnyEvent::HTTP;
use AnyEvent;
use AnyEvent::Strict;
use strict;
use warnings;
my $w = AE::timer 1, 1, sub { print "lala\n" };
AnyEvent::Loop::run;AnyEvent
use AnyEvent::Loop;
use AnyEvent::HTTP;
use AnyEvent;
use AnyEvent::Strict;
use strict;
use warnings;
my $w = AE::timer 1, 0, sub { print "lala\n" };
for(my $i = 0; $i < 2; $i++)
{
print "iteration number: $i\n";
http_get "http://www.nethype.de/", sub{ print "shalala \n";}
}
AnyEvent::Loop::run;Bonus
use AnyEvent::HTTPD;
my $httpd = AnyEvent::HTTPD->new (port => 9090);
$httpd->reg_cb (
'/' => sub {
my ($httpd, $req) = @_;
$req->respond ({ content => ['text/html',
"<html><body><h1>Hello World!</h1>"
. "<a href=\"/test\">another test page</a>"
. "</body></html>"
]});
},
'/test' => sub {
my ($httpd, $req) = @_;
$req->respond ({ content => ['text/html',
"<html><body><h1>Test page</h1>"
. "<a href=\"/\">Back to the main page</a>"
. "</body></html>"
]});
},
'/zlatin' => sub {
my ($httpd, $req) = @_;
$req->respond({
content => ['text/html', '<b>Tonight at eleven...</b>']
});
},
);
$httpd->run; # making a AnyEvent condition variable would also workBonus 2
use AnyEvent::Loop;
use AnyEvent;
use AnyEvent::Strict;
use AnyEvent::DBI;
use Data::Dumper;
use strict;
use warnings;
my $dbh = new AnyEvent::DBI "DBI:SQLite:dbname=ae_test.db", "foo", "bar";
$dbh->exec ("select now()", sub {
my ($dbh, $rows, $rv) = @_;
$#_ or die "failure: $@";
for my $row (@$rows)
{
print Dumper($row);
}
});
AnyEvent::Loop::run;AnyEvent
By Zlatin Stanimirov
AnyEvent
- 850