AnyEvent

 view release on metacpan or  search on metacpan

lib/AnyEvent/Intro.pod  view on Meta::CPAN

=head1 What is AnyEvent?

If you don't care for the whys and want to see code, skip this section!

AnyEvent is first of all just a framework to do event-based
programming. Typically such frameworks are an all-or-nothing thing: If you
use one such framework, you can't (easily, or even at all) use another in
the same program.

AnyEvent is different - it is a thin abstraction layer on top of other
event loops, just like DBI is an abstraction of many different database
APIs. Its main purpose is to move the choice of the underlying framework
(the event loop) from the module author to the program author using the
module.

That means you can write code that uses events to control what it
does, without forcing other code in the same program to use the same
underlying framework as you do - i.e. you can create a Perl module
that is event-based using AnyEvent, and users of that module can still
choose between using L<Gtk2>, L<Tk>, L<Event> (or run inside Irssi or
rxvt-unicode) or any other supported event loop. AnyEvent even comes with
its own pure-perl event loop implementation, so your code works regardless
of other modules that might or might not be installed. The latter is
important, as AnyEvent does not have any hard dependencies to other
modules, which makes it easy to install, for example, when you lack a C
compiler. No matter what environment, AnyEvent will just cope with it.

A typical limitation of existing Perl modules such as L<Net::IRC> is that
they come with their own event loop: In L<Net::IRC>, a program which uses
it needs to start the event loop of L<Net::IRC>. That means that one
cannot integrate this module into a L<Gtk2> GUI for instance, as that
module, too, enforces the use of its own event loop (namely L<Glib>).

Another example is L<LWP>: it provides no event interface at all. It's
a pure blocking HTTP (and FTP etc.) client library, which usually means
that you either have to start another process or have to fork for a HTTP
request, or use threads (e.g. L<Coro::LWP>), if you want to do something
else while waiting for the request to finish.

The motivation behind these designs is often that a module doesn't want
to depend on some complicated XS-module (Net::IRC), or that it doesn't
want to force the user to use some specific event loop at all (LWP), out
of fear of severly limiting the usefulness of the module: If your module
requires Glib, it will not run in a Tk program.

L<AnyEvent> solves this dilemma, by B<not> forcing module authors to
either:

=over 4

=item - write their own event loop (because it guarantees the availability
of an event loop everywhere - even on windows with no extra modules
installed).

=item - choose one specific event loop (because AnyEvent works with most
event loops available for Perl).

=back

If the module author uses L<AnyEvent> for all his (or her) event needs
(IO events, timers, signals, ...) then all other modules can just use
his module and don't have to choose an event loop or adapt to his event
loop. The choice of the event loop is ultimately made by the program
author who uses all the modules and writes the main program. And even
there he doesn't have to choose, he can just let L<AnyEvent> choose the
most efficient event loop available on the system.

Read more about this in the main documentation of the L<AnyEvent> module.


=head1 Introduction to Event-Based Programming

So what exactly is programming using events? It quite simply means that
instead of your code actively waiting for something, such as the user
entering something on STDIN:

   $| = 1; print "enter your name> ";

   my $name = <STDIN>;

You instead tell your event framework to notify you in the event of some
data being available on STDIN, by using a callback mechanism:

   use AnyEvent;

   $| = 1; print "enter your name> ";

   my $name;

   my $wait_for_input = AnyEvent->io (
      fh   => \*STDIN, # which file handle to check
      poll => "r",     # which event to wait for ("r"ead data)
      cb   => sub {    # what callback to execute
         $name = <STDIN>; # read it
      }
   );

   # do something else here

Looks more complicated, and surely is, but the advantage of using events
is that your program can do something else instead of waiting for input
(side note: combining AnyEvent with a thread package such as Coro can
recoup much of the simplicity, effectively getting the best of two
worlds).

Waiting as done in the first example is also called "blocking" the process
because you "block"/keep your process from executing anything else while
you do so.

The second example avoids blocking by only registering interest in a read
event, which is fast and doesn't block your process. The callback will
be called only when data is available and can be read without blocking.

The "interest" is represented by an object returned by C<< AnyEvent->io
>> called a "watcher" object - thus named because it "watches" your
file handle (or other event sources) for the event you are interested in.

In the example above, we create an I/O watcher by calling the C<<
AnyEvent->io >> method. A lack of further interest in some event is
expressed by simply forgetting about its watcher, for example by
C<undef>-ing the only variable it is stored in. AnyEvent will

lib/AnyEvent/Intro.pod  view on Meta::CPAN

Instead of waiting for a condition variable, the program enters the Gtk2
main loop by calling C<< Gtk2->main >>, which will block the program and
wait for events to arrive.

This also shows that AnyEvent is quite flexible - you didn't have to do
anything to make the AnyEvent watcher use Gtk2 (actually Glib) - it just
worked.

Admittedly, the example is a bit silly - who would want to read names
from standard input in a Gtk+ application? But imagine that instead of
doing that, you make an HTTP request in the background and display its
results. In fact, with event-based programming you can make many
HTTP requests in parallel in your program and still provide feedback to
the user and stay interactive.

And in the next part you will see how to do just that - by implementing an
HTTP request, on our own, with the utility modules AnyEvent comes with.

Before that, however, let's briefly look at how you would write your
program using only AnyEvent, without ever calling some other event
loop's run function.

In the example using condition variables, we used those to start waiting
for events, and in fact, condition variables are the solution:

   my $quit_program = AnyEvent->condvar;

   # create AnyEvent watchers (or not) here

   $quit_program->recv;

If any of your watcher callbacks decide to quit (this is often
called an "unloop" in other frameworks), they can just call C<<
$quit_program->send >>. Of course, they could also decide not to and
call C<exit> instead, or they could decide never to quit (e.g. in a
long-running daemon program).

If you don't need some clean quit functionality and just want to run the
event loop, you can do this:

   AnyEvent->condvar->recv;

And this is, in fact, the closest to the idea of a main loop run
function that AnyEvent offers.

=head2 Timers and other event sources

So far, we have used only I/O watchers. These are useful mainly to find
out whether a socket has data to read, or space to write more data. On sane
operating systems this also works for console windows/terminals (typically
on standard input), serial lines, all sorts of other devices, basically
almost everything that has a file descriptor but isn't a file itself. (As
usual, "sane" excludes windows - on that platform you would need different
functions for all of these, complicating code immensely - think "socket
only" on windows).

However, I/O is not everything - the second most important event source is
the clock. For example when doing an HTTP request you might want to time
out when the server doesn't answer within some predefined amount of time.

In AnyEvent, timer event watchers are created by calling the C<<
AnyEvent->timer >> method:

   use AnyEvent;

   my $cv = AnyEvent->condvar;

   my $wait_one_and_a_half_seconds = AnyEvent->timer (
      after => 1.5,  # after how many seconds to invoke the cb?
      cb    => sub { # the callback to invoke
         $cv->send;
      },
   );

   # can do something else here

   # now wait till our time has come
   $cv->recv;

Unlike I/O watchers, timers are only interested in the amount of seconds
they have to wait. When (at least) that amount of time has passed,
AnyEvent will invoke your callback.

Unlike I/O watchers, which will call your callback as many times as there
is data available, timers are normally one-shot: after they have "fired"
once and invoked your callback, they are dead and no longer do anything.

To get a repeating timer, such as a timer firing roughly once per second,
you can specify an C<interval> parameter:

   my $once_per_second = AnyEvent->timer (
      after => 0,    # first invoke ASAP
      interval => 1, # then invoke every second
      cb    => sub { # the callback to invoke
         $cv->send;
      },
   );

=head3 More esoteric sources

AnyEvent also has some other, more esoteric event sources you can tap
into: signal, child and idle watchers.

Signal watchers can be used to wait for "signal events", which means
your process was sent a signal (such as C<SIGTERM> or C<SIGUSR1>).

Child-process watchers wait for a child process to exit. They are useful
when you fork a separate process and need to know when it exits, but you
do not want to wait for that by blocking.

Idle watchers invoke their callback when the event loop has handled all
outstanding events, polled for new events and didn't find any, i.e., when
your process is otherwise idle. They are useful if you want to do some
non-trivial data processing that can be done when your program doesn't
have anything better to do.

All these watcher types are described in detail in the main L<AnyEvent>
manual page.

Sometimes you also need to know what the current time is: C<<
AnyEvent->now >> returns the time the event toolkit uses to schedule
relative timers, and is usually what you want. It is often cached (which
means it can be a bit outdated). In that case, you can use the more costly
C<< AnyEvent->time >> method which will ask your operating system for the
current time, which is slower, but also more up to date.


=head1 Network programming and AnyEvent

So far you have seen how to register event watchers and handle events.

This is a great foundation to write network clients and servers, and might
be all that your module (or program) ever requires, but writing your own
I/O buffering again and again becomes tedious, not to mention that it
attracts errors.

While the core L<AnyEvent> module is still small and self-contained,
the distribution comes with some very useful utility modules such as
L<AnyEvent::Handle>, L<AnyEvent::DNS> and L<AnyEvent::Socket>. These can
make your life as a non-blocking network programmer a lot easier.

Here is a quick overview of these three modules:

=head2 L<AnyEvent::DNS>

This module allows fully asynchronous DNS resolution. It is used mainly by
L<AnyEvent::Socket> to resolve hostnames and service ports for you, but is
a great way to do other DNS resolution tasks, such as reverse lookups of
IP addresses for log files.

=head2 L<AnyEvent::Handle>

This module handles non-blocking IO on (socket-, pipe- etc.) file handles
in an event based manner. It provides a wrapper object around your file
handle that provides queueing and buffering of incoming and outgoing data
for you.

It also implements the most common data formats, such as text lines, or
fixed and variable-width data blocks.

=head2 L<AnyEvent::Socket>

This module provides you with functions that handle socket creation
and IP address magic. The two main functions are C<tcp_connect> and
C<tcp_server>. The former will connect a (streaming) socket to an internet
host for you and the later will make a server socket for you, to accept
connections.

This module also comes with transparent IPv6 support, this means: If you
write your programs with this module, you will be IPv6 ready without doing
anything special.

It also works around a lot of portability quirks (especially on the
windows platform), which makes it even easier to write your programs in a
portable way (did you know that windows uses different error codes for all
socket functions and that Perl does not know about these? That "Unknown
error 10022" (which is C<WSAEINVAL>) can mean that our C<connect> call was
successful? That unsuccessful TCP connects might never be reported back
to your program? That C<WSAEINPROGRESS> means your C<connect> call was
ignored instead of being in progress? AnyEvent::Socket works around all of
these Windows/Perl bugs for you).



( run in 0.777 second using v1.01-cache-2.11-cpan-df04353d9ac )