ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent/Intro.pod
Revision: 1.24
Committed: Fri Jul 24 23:43:59 2009 UTC (14 years, 10 months ago) by root
Branch: MAIN
Changes since 1.23: +100 -92 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.21 =head1 NAME
2    
3     AnyEvent::Intro - an introductory tutorial to AnyEvent
4    
5 root 1.2 =head1 Introduction to AnyEvent
6 root 1.1
7 root 1.2 This is a tutorial that will introduce you to the features of AnyEvent.
8 root 1.1
9 root 1.2 The first part introduces the core AnyEvent module (after swamping you a
10 root 1.17 bit in evangelism), which might already provide all you ever need. If you
11     are only interested in AnyEvent's event handling capabilities, read no
12     further.
13 root 1.1
14 root 1.2 The second part focuses on network programming using sockets, for which
15 root 1.17 AnyEvent offers a lot of support you can use, and a lot of workarounds
16     around portability quirks.
17 root 1.2
18    
19     =head1 What is AnyEvent?
20    
21 root 1.10 If you don't care for the whys and want to see code, skip this section!
22 root 1.2
23     AnyEvent is first of all just a framework to do event-based
24     programming. Typically such frameworks are an all-or-nothing thing: If you
25     use one such framework, you can't (easily, or even at all) use another in
26     the same program.
27    
28     AnyEvent is different - it is a thin abstraction layer above all kinds
29     of event loops. Its main purpose is to move the choice of the underlying
30     framework (the event loop) from the module author to the program author
31     using the module.
32    
33     That means you can write code that uses events to control what it
34     does, without forcing other code in the same program to use the same
35     underlying framework as you do - i.e. you can create a Perl module
36     that is event-based using AnyEvent, and users of that module can still
37     choose between using L<Gtk2>, L<Tk>, L<Event> or no event loop at
38     all: AnyEvent comes with its own event loop implementation, so your
39     code works regardless of other modules that might or might not be
40     installed. The latter is important, as AnyEvent does not have any
41     dependencies to other modules, which makes it easy to install, for
42     example, when you lack a C compiler.
43    
44     A typical problem with Perl modules such as L<Net::IRC> is that they
45     come with their own event loop: In L<Net::IRC>, the program who uses it
46     needs to start the event loop of L<Net::IRC>. That means that one cannot
47     integrate this module into a L<Gtk2> GUI for instance, as that module,
48     too, enforces the use of its own event loop (namely L<Glib>).
49 root 1.1
50     Another example is L<LWP>: it provides no event interface at all. It's a
51     pure blocking HTTP (and FTP etc.) client library, which usually means that
52     you either have to start a thread or have to fork for a HTTP request, or
53     use L<Coro::LWP>, if you want to do something else while waiting for the
54     request to finish.
55    
56     The motivation behind these designs is often that a module doesn't want to
57     depend on some complicated XS-module (Net::IRC), or that it doesn't want
58 root 1.2 to force the user to use some specific event loop at all (LWP).
59 root 1.1
60 root 1.2 L<AnyEvent> solves this dilemma, by B<not> forcing module authors to either
61 root 1.1
62     =over 4
63    
64 root 1.11 =item - write their own event loop (because guarantees to offer one
65 root 1.2 everywhere - even on windows).
66 root 1.1
67 root 1.11 =item - choose one fixed event loop (because AnyEvent works with all
68 root 1.2 important event loops available for Perl, and adding others is trivial).
69 root 1.1
70     =back
71    
72 root 1.2 If the module author uses L<AnyEvent> for all his event needs (IO events,
73     timers, signals, ...) then all other modules can just use his module and
74     don't have to choose an event loop or adapt to his event loop. The choice
75     of the event loop is ultimately made by the program author who uses all
76     the modules and writes the main program. And even there he doesn't have to
77     choose, he can just let L<AnyEvent> choose the best available event loop
78     for him.
79 root 1.1
80     Read more about this in the main documentation of the L<AnyEvent> module.
81    
82    
83 root 1.2 =head1 Introduction to Event-Based Programming
84    
85     So what exactly is programming using events? It quite simply means that
86     instead of your code actively waiting for something, such as the user
87     entering something on STDIN:
88    
89     $| = 1; print "enter your name> ";
90    
91     my $name = <STDIN>;
92    
93     You instead tell your event framework to notify you in the event of some
94     data being available on STDIN, by using a callback mechanism:
95    
96     use AnyEvent;
97    
98     $| = 1; print "enter your name> ";
99    
100     my $name;
101    
102     my $wait_for_input = AnyEvent->io (
103     fh => \*STDIN, # which file handle to check
104     poll => "r", # which event to wait for ("r"ead data)
105     cb => sub { # what callback to execute
106     $name = <STDIN>; # read it
107     }
108     );
109    
110     # do something else here
111    
112     Looks more complicated, and surely is, but the advantage of using events
113 root 1.22 is that your program can do something else instead of waiting for input
114     (side note: combining AnyEvent with a thread package such as Coro can
115     recoup much of the simplicity, effectively getting the best of two
116     worlds).
117    
118     Waiting as done in the first example is also called "blocking" the process
119     because you "block"/keep your process from executing anything else while
120     you do so.
121 root 1.2
122 root 1.22 The second example avoids blocking by only registering interest in a read
123 root 1.2 event, which is fast and doesn't block your process. Only when read data
124     is available will the callback be called, which can then proceed to read
125     the data.
126    
127     The "interest" is represented by an object returned by C<< AnyEvent->io
128     >> called a "watcher" object - called like that because it "watches" your
129     file handle (or other event sources) for the event you are interested in.
130    
131     In the example above, we create an I/O watcher by calling the C<<
132 root 1.22 AnyEvent->io >> method. Disinterest in some event is simply expressed
133     by forgetting about the watcher, for example, by C<undef>'ing the only
134     variable it is stored in. AnyEvent will automatically clean up the watcher
135     if it is no longer used, much like Perl closes your file handles if you no
136     longer use them anywhere.
137 root 1.2
138 root 1.18 =head3 A short note on callbacks
139    
140     A common issue that hits people is the problem of passing parameters
141     to callbacks. Programmers used to languages such as C or C++ are often
142     used to a style where one passes the address of a function (a function
143     reference) and some data value, e.g.:
144    
145     sub callback {
146     my ($arg) = @_;
147    
148     $arg->method;
149     }
150    
151     my $arg = ...;
152    
153     call_me_back_later \&callback, $arg;
154    
155     This is clumsy, as the place where behaviour is specified (when the
156     callback is registered) is often far away from the place where behaviour
157     is implemented. It also doesn't use Perl syntax to invoke the code. There
158     is also an abstraction penalty to pay as one has to I<name> the callback,
159     which often is unnecessary and leads to nonsensical or duplicated names.
160    
161     In Perl, one can specify behaviour much more directly by using
162     I<closures>. Closures are code blocks that take a reference to the
163 root 1.22 enclosing scope(s) when they are created. This means lexical variables in
164     scope at the time of creating the closure can simply be used inside the
165     closure:
166 root 1.18
167     my $arg = ...;
168    
169     call_me_back_later sub { $arg->method };
170    
171 root 1.22 Under most circumstances, closures are faster, use fewer resources and
172 root 1.18 result in much clearer code then the traditional approach. Faster,
173     because parameter passing and storing them in local variables in Perl
174 root 1.22 is relatively slow. Fewer resources, because closures take references
175     to existing variables without having to create new ones, and clearer
176     code because it is immediately obvious that the second example calls the
177 root 1.18 C<method> method when the callback is invoked.
178    
179     Apart from these, the strongest argument for using closures with AnyEvent
180     is that AnyEvent does not allow passing parameters to the callback, so
181     closures are the only way to achieve that in most cases :->
182    
183    
184 root 1.19 =head3 A hint on debugging
185    
186     AnyEvent does, by default, not do any argument checking. This can lead to
187 root 1.22 strange and unexpected results especially if you are trying to learn your
188 root 1.19 ways with AnyEvent.
189    
190 root 1.24 AnyEvent supports a special "strict" mode - off by default - which does very
191 root 1.22 strict argument checking, at the expense of being somewhat slower. During
192     development, however, this mode is very useful.
193 root 1.19
194     You can enable this strict mode either by having an environment variable
195     C<PERL_ANYEVENT_STRICT> with a true value in your environment:
196    
197     PERL_ANYEVENT_STRICT=1 perl test.pl
198    
199     Or you can write C<use AnyEvent::Strict> in your program, which has the
200     same effect (do not do this in production, however).
201    
202    
203 root 1.2 =head2 Condition Variables
204    
205 root 1.22 Back to the I/O watcher example: The code is not yet a fully working
206     program, and will not work as-is. The reason is that your callback will
207     not be invoked out of the blue, you have to run the event loop. Also,
208     event-based programs sometimes have to block, too, as when there simply is
209     nothing else to do and everything waits for some events, it needs to block
210     the process as well until new events arrive.
211 root 1.2
212     In AnyEvent, this is done using condition variables. Condition variables
213     are named "condition variables" because they represent a condition that is
214     initially false and needs to be fulfilled.
215    
216 root 1.10 You can also call them "merge points", "sync points", "rendezvous ports"
217     or even callbacks and many other things (and they are often called like
218     this in other frameworks). The important point is that you can create them
219     freely and later wait for them to become true.
220 root 1.2
221     Condition variables have two sides - one side is the "producer" of the
222 root 1.18 condition (whatever code detects and flags the condition), the other side
223     is the "consumer" (the code that waits for that condition).
224 root 1.2
225     In our example in the previous section, the producer is the event callback
226 root 1.18 and there is no consumer yet - let's change that right now:
227 root 1.2
228     use AnyEvent;
229    
230     $| = 1; print "enter your name> ";
231    
232     my $name;
233    
234     my $name_ready = AnyEvent->condvar;
235    
236     my $wait_for_input = AnyEvent->io (
237     fh => \*STDIN,
238     poll => "r",
239     cb => sub {
240     $name = <STDIN>;
241     $name_ready->send;
242     }
243     );
244    
245     # do something else here
246    
247     # now wait until the name is available:
248     $name_ready->recv;
249    
250     undef $wait_for_input; # watche rno longer needed
251    
252     print "your name is $name\n";
253    
254     This program creates an AnyEvent condvar by calling the C<<
255     AnyEvent->condvar >> method. It then creates a watcher as usual, but
256     inside the callback it C<send>'s the C<$name_ready> condition variable,
257 root 1.22 which causes whoever is waiting on it to continue.
258 root 1.2
259 root 1.22 The "whoever" in this case is the code that follows, which calls C<<
260 root 1.2 $name_ready->recv >>: The producer calls C<send>, the consumer calls
261     C<recv>.
262    
263     If there is no C<$name> available yet, then the call to C<<
264     $name_ready->recv >> will halt your program until the condition becomes
265     true.
266    
267     As the names C<send> and C<recv> imply, you can actually send and receive
268     data using this, for example, the above code could also be written like
269     this, without an extra variable to store the name in:
270    
271     use AnyEvent;
272    
273     $| = 1; print "enter your name> ";
274    
275     my $name_ready = AnyEvent->condvar;
276    
277     my $wait_for_input = AnyEvent->io (
278     fh => \*STDIN, poll => "r",
279 root 1.20 cb => sub { $name_ready->send (scalar <STDIN>) }
280 root 1.2 );
281    
282     # do something else here
283    
284     # now wait and fetch the name
285     my $name = $name_ready->recv;
286    
287     undef $wait_for_input; # watche rno longer needed
288    
289     print "your name is $name\n";
290    
291     You can pass any number of arguments to C<send>, and everybody call to
292     C<recv> will return them.
293    
294     =head2 The "main loop"
295    
296     Most event-based frameworks have something called a "main loop" or "event
297     loop run function" or something similar.
298    
299     Just like in C<recv> AnyEvent, these functions need to be called
300     eventually so that your event loop has a chance of actually looking for
301     those events you are interested in.
302    
303     For example, in a L<Gtk2> program, the above example could also be written
304     like this:
305    
306     use Gtk2 -init;
307     use AnyEvent;
308    
309     ############################################
310     # create a window and some label
311    
312     my $window = new Gtk2::Window "toplevel";
313     $window->add (my $label = new Gtk2::Label "soon replaced by name");
314    
315     $window->show_all;
316    
317     ############################################
318     # do our AnyEvent stuff
319    
320     $| = 1; print "enter your name> ";
321    
322     my $name_ready = AnyEvent->condvar;
323    
324     my $wait_for_input = AnyEvent->io (
325     fh => \*STDIN, poll => "r",
326     cb => sub {
327     # set the label
328     $label->set_text (scalar <STDIN>);
329     print "enter another name> ";
330     }
331     );
332    
333     ############################################
334     # Now enter Gtk2's event loop
335    
336     main Gtk2;
337    
338     No condition variable anywhere in sight - instead, we just read a line
339     from STDIN and replace the text in the label. In fact, since nobody
340     C<undef>'s C<$wait_for_input> you can enter multiple lines.
341    
342     Instead of waiting for a condition variable, the program enters the Gtk2
343     main loop by calling C<< Gtk2->main >>, which will block the program and
344     wait for events to arrive.
345    
346     This also shows that AnyEvent is quite flexible - you didn't have anything
347     to do to make the AnyEvent watcher use Gtk2 (actually Glib) - it just
348     worked.
349    
350     Admittedly, the example is a bit silly - who would want to read names
351 root 1.22 from standard input in a Gtk+ application. But imagine that instead of
352 root 1.2 doing that, you would make a HTTP request in the background and display
353     it's results. In fact, with event-based programming you can make many
354     http-requests in parallel in your program and still provide feedback to
355     the user and stay interactive.
356    
357 root 1.22 And in the next part you will see how to do just that - by implementing an
358 root 1.2 HTTP request, on our own, with the utility modules AnyEvent comes with.
359    
360 root 1.4 Before that, however, let's briefly look at how you would write your
361 root 1.2 program with using only AnyEvent, without ever calling some other event
362     loop's run function.
363    
364 root 1.22 In the example using condition variables, we used those to start waiting
365     for events, and in fact, condition variables are the solution:
366 root 1.2
367     my $quit_program = AnyEvent->condvar;
368    
369     # create AnyEvent watchers (or not) here
370    
371     $quit_program->recv;
372    
373 root 1.22 If any of your watcher callbacks decide to quit (this is often
374     called an "unloop" in other frameworks), they can simply call C<<
375     $quit_program->send >>. Of course, they could also decide not to and
376 root 1.2 simply call C<exit> instead, or they could decide not to quit, ever (e.g.
377     in a long-running daemon program).
378    
379 root 1.22 If you don't need some clean quit functionality and just want to run the
380     event loop, you can simply do this:
381 root 1.2
382     AnyEvent->condvar->recv;
383    
384     And this is, in fact, closest to the idea of a main loop run function that
385     AnyEvent offers.
386    
387     =head2 Timers and other event sources
388    
389     So far, we have only used I/O watchers. These are useful mainly to find
390 root 1.10 out whether a Socket has data to read, or space to write more data. On sane
391 root 1.2 operating systems this also works for console windows/terminals (typically
392     on standard input), serial lines, all sorts of other devices, basically
393     almost everything that has a file descriptor but isn't a file itself. (As
394     usual, "sane" excludes windows - on that platform you would need different
395 root 1.10 functions for all of these, complicating code immensely - think "socket
396 root 1.2 only" on windows).
397    
398 root 1.10 However, I/O is not everything - the second most important event source is
399 root 1.2 the clock. For example when doing an HTTP request you might want to time
400 root 1.10 out when the server doesn't answer within some predefined amount of time.
401 root 1.2
402     In AnyEvent, timer event watchers are created by calling the C<<
403     AnyEvent->timer >> method:
404    
405     use AnyEvent;
406    
407     my $cv = AnyEvent->condvar;
408    
409     my $wait_one_and_a_half_seconds = AnyEvent->timer (
410     after => 1.5, # after how many seconds to invoke the cb?
411     cb => sub { # the callback to invoke
412     $cv->send;
413     },
414     );
415    
416 root 1.10 # can do something else here
417 root 1.2
418     # now wait till our time has come
419     $cv->recv;
420    
421     Unlike I/O watchers, timers are only interested in the amount of seconds
422 root 1.22 they have to wait. When (at least) that amount of time has passed,
423     AnyEvent will invoke your callback.
424 root 1.2
425     Unlike I/O watchers, which will call your callback as many times as there
426 root 1.22 is data available, timers are normally one-shot: after they have "fired"
427     once and invoked your callback, they are dead and no longer do anything.
428 root 1.2
429     To get a repeating timer, such as a timer firing roughly once per second,
430 root 1.22 you can specify an C<interval> parameter:
431 root 1.2
432 root 1.22 my $once_per_second = AnyEvent->timer (
433     after => 0, # first invoke ASAP
434     interval => 1, # then invoke every second
435     cb => sub { # the callback to invoke
436     $cv->send;
437     },
438     );
439 root 1.2
440     =head3 More esoteric sources
441    
442     AnyEvent also has some other, more esoteric event sources you can tap
443 root 1.22 into: signal, child and idle watchers.
444 root 1.2
445     Signal watchers can be used to wait for "signal events", which simply
446 root 1.7 means your process got send a signal (such as C<SIGTERM> or C<SIGUSR1>).
447 root 1.2
448 root 1.22 Child-process watchers wait for a child process to exit. They are useful
449     when you fork a separate process and need to know when it exits, but you
450     do not wait for that by blocking.
451    
452     Idle watchers invoke their callback when the event loop has handled all
453     outstanding events, polled for new events and didn't find any, i.e., when
454     your process is otherwise idle. They are useful if you want to do some
455     non-trivial data processing that can be done when your program doesn't
456     have anything better to do.
457    
458     All these watcher types are described in detail in the main L<AnyEvent>
459     manual page.
460    
461     Sometimes you also need to know what the current time is: C<<
462     AnyEvent->now >> returns the time the event toolkit uses to schedule
463     relative timers, and is usually what you want. It is often cached (which
464     means it can be a bit outdated). In that case, you can use the more costly
465     C<< AnyEvent->time >> method which will ask your operating system for the
466     current time, which is slower, but also more up to date.
467 root 1.2
468     =head1 Network programming and AnyEvent
469    
470 root 1.3 So far you have seen how to register event watchers and handle events.
471 root 1.1
472 root 1.22 This is a great foundation to write network clients and servers, and might
473     be all that your module (or program) ever requires, but writing your own
474     I/O buffering again and again becomes tedious, not to mention that it
475     attracts errors.
476 root 1.3
477     While the core L<AnyEvent> module is still small and self-contained,
478     the distribution comes with some very useful utility modules such as
479     L<AnyEvent::Handle>, L<AnyEvent::DNS> and L<AnyEvent::Socket>. These can
480     make your life as non-blocking network programmer a lot easier.
481    
482 root 1.4 Here is a quick overview over these three modules:
483    
484     =head2 L<AnyEvent::DNS>
485    
486     This module allows fully asynchronous DNS resolution. It is used mainly by
487     L<AnyEvent::Socket> to resolve hostnames and service ports for you, but is
488     a great way to do other DNS resolution tasks, such as reverse lookups of
489     IP addresses for log files.
490 root 1.1
491 root 1.2 =head2 L<AnyEvent::Handle>
492 root 1.1
493 root 1.22 This module handles non-blocking IO on (socket-, pipe- etc.) file handles
494     in an event based manner. It provides a wrapper object around your file
495     handle that provides queueing and buffering of incoming and outgoing data
496     for you.
497 root 1.1
498 root 1.4 It also implements the most common data formats, such as text lines, or
499     fixed and variable-width data blocks.
500 root 1.1
501 root 1.2 =head2 L<AnyEvent::Socket>
502 root 1.1
503     This module provides you with functions that handle socket creation
504     and IP address magic. The two main functions are C<tcp_connect> and
505     C<tcp_server>. The former will connect a (streaming) socket to an internet
506     host for you and the later will make a server socket for you, to accept
507     connections.
508    
509     This module also comes with transparent IPv6 support, this means: If you
510     write your programs with this module, you will be IPv6 ready without doing
511 root 1.4 anything special.
512 root 1.1
513     It also works around a lot of portability quirks (especially on the
514     windows platform), which makes it even easier to write your programs in a
515 root 1.4 portable way (did you know that windows uses different error codes for all
516     socket functions and that Perl does not know about these? That "Unknown
517     error 10022" (which is C<WSAEINVAL>) can mean that our C<connect> call was
518     successful? That unsuccessful TCP connects might never be reported back
519     to your program? That C<WSAEINPROGRESS> means your C<connect> call was
520     ignored instead of being in progress? AnyEvent::Socket works around all of
521     these Windows/Perl bugs for you).
522    
523 root 1.11 =head2 Implementing a parallel finger client with non-blocking connects
524 root 1.16 and AnyEvent::Socket
525 root 1.4
526     The finger protocol is one of the simplest protocols in use on the
527     internet. Or in use in the past, as almost nobody uses it anymore.
528    
529     It works by connecting to the finger port on another host, writing a
530     single line with a user name and then reading the finger response, as
531     specified by that user. OK, RFC 1288 specifies a vastly more complex
532     protocol, but it basically boils down to this:
533    
534 root 1.22 # telnet kernel.org finger
535     Trying 204.152.191.37...
536     Connected to kernel.org (204.152.191.37).
537 root 1.4 Escape character is '^]'.
538 root 1.22
539     The latest stable version of the Linux kernel is: [...]
540 root 1.4 Connection closed by foreign host.
541    
542 root 1.22 So let's write a little AnyEvent function that makes a finger request:
543 root 1.4
544     use AnyEvent;
545     use AnyEvent::Socket;
546    
547     sub finger($$) {
548     my ($user, $host) = @_;
549    
550     # use a condvar to return results
551     my $cv = AnyEvent->condvar;
552    
553     # first, connect to the host
554     tcp_connect $host, "finger", sub {
555 root 1.8 # the callback receives the socket handle - or nothing
556 root 1.4 my ($fh) = @_
557     or return $cv->send;
558    
559     # now write the username
560     syswrite $fh, "$user\015\012";
561    
562     my $response;
563    
564     # register a read watcher
565     my $read_watcher; $read_watcher = AnyEvent->io (
566     fh => $fh,
567     poll => "r",
568     cb => sub {
569     my $len = sysread $fh, $response, 1024, length $response;
570    
571     if ($len <= 0) {
572     # we are done, or an error occured, lets ignore the latter
573     undef $read_watcher; # no longer interested
574     $cv->send ($response); # send results
575     }
576     },
577     );
578     };
579    
580     # pass $cv to the caller
581     $cv
582     }
583    
584 root 1.11 That's a mouthful! Let's dissect this function a bit, first the overall
585     function and execution flow:
586 root 1.4
587     sub finger($$) {
588     my ($user, $host) = @_;
589    
590     # use a condvar to return results
591     my $cv = AnyEvent->condvar;
592    
593     # first, connect to the host
594     tcp_connect $host, "finger", sub {
595     ...
596     };
597    
598     $cv
599     }
600    
601 root 1.11 This isn't too complicated, just a function with two parameters, that
602 root 1.4 creates a condition variable, returns it, and while it does that,
603 root 1.11 initiates a TCP connect to C<$host>. The condition variable will be used
604     by the caller to receive the finger response, but one could equally well
605     pass a third argument, a callback, to the function.
606 root 1.4
607 root 1.11 Since we are programming event'ish, we do not wait for the connect to
608     finish - it could block the program for a minute or longer!
609    
610     Instead, we pass the callback it should invoke when the connect is done to
611     C<tcp_connect>. If it is successful, that callback gets called with the
612 root 1.5 socket handle as first argument, otherwise, nothing will be passed to our
613 root 1.11 callback. The important point is that it will always be called as soon as
614     the outcome of the TCP connect is known.
615    
616     This style of programming is also called "continuation style": the
617 root 1.22 "continuation" is simply the way the program continues - normally at the
618     next line after some statement (the exception is loops or things like
619     C<return>). When we are interested in events, however, we instead specify
620     the "continuation" of our program by passing a closure, which makes that
621     closure the "continuation" of the program.
622    
623     The C<tcp_connect> call is like saying "return now, and when the
624     connection is established or it failed, continue there".
625 root 1.4
626 root 1.11 Now let's look at the callback/closure in more detail:
627 root 1.4
628 root 1.11 # the callback receives the socket handle - or nothing
629 root 1.4 my ($fh) = @_
630     or return $cv->send;
631    
632 root 1.5 The first thing the callback does is indeed save the socket handle in
633     C<$fh>. When there was an error (no arguments), then our instinct as
634 root 1.11 expert Perl programmers would tell us to C<die>:
635 root 1.4
636     my ($fh) = @_
637     or die "$host: $!";
638 root 1.1
639 root 1.11 While this would give good feedback to the user (if he happens to watch
640     standard error), our program would probably stop working here, as we never
641     report the results to anybody, certainly not the caller of our C<finger>
642     function, and most event loops continue even after a C<die>!
643    
644     This is why we instead C<return>, but also call C<< $cv->send >> without
645     any arguments to signal to the condvar consumer that something bad has
646 root 1.22 happened. The return value of C<< $cv->send >> is irrelevant, as is
647     the return value of our callback. The C<return> statement is simply
648     used for the side effect of, well, returning immediately from the
649     callback. Checking for errors and handling them this way is very common,
650     which is why this compact idiom is so handy.
651 root 1.4
652     As the next step in the finger protocol, we send the username to the
653 root 1.22 finger daemon on the other side of our connection (the kernel.org finger
654     service doesn't actually wait for a username, but the net is running out
655     of finger servers fast):
656 root 1.4
657     syswrite $fh, "$user\015\012";
658    
659 root 1.11 Note that this isn't 100% clean socket programming - the socket could,
660     for whatever reasons, not accept our data. When writing a small amount
661     of data like in this example it doesn't matter, as a socket buffer is
662     almost always big enough for a mere "username", but for real-world
663     cases you might need to implement some kind of write buffering - or use
664     L<AnyEvent::Handle>, which handles these matters for you, as shown in the
665     next section.
666 root 1.4
667 root 1.11 What we I<do> have to do is to implement our own read buffer - the response
668 root 1.4 data could arrive late or in multiple chunks, and we cannot just wait for
669     it (event-based programming, you know?).
670    
671     To do that, we register a read watcher on the socket which waits for data:
672    
673     my $read_watcher; $read_watcher = AnyEvent->io (
674     fh => $fh,
675     poll => "r",
676    
677     There is a trick here, however: the read watcher isn't stored in a global
678     variable, but in a local one - if the callback returns, it would normally
679     destroy the variable and its contents, which would in turn unregister our
680 root 1.5 watcher.
681 root 1.4
682     To avoid that, we C<undef>ine the variable in the watcher callback. This
683 root 1.22 means that, when the C<tcp_connect> callback returns, perl thinks (quite
684     correctly) that the read watcher is still in use - namely in the callback,
685     and thus keeps it alive even if nothing else in the program refers to it
686     anymore (it is much like Baron Münchhausen keeping himself from dying by
687     pulling himself out of a swamp).
688 root 1.4
689 root 1.11 The trick, however, is that instead of:
690    
691     my $read_watcher = AnyEvent->io (...
692    
693     The program does:
694    
695     my $read_watcher; $read_watcher = AnyEvent->io (...
696    
697     The reason for this is a quirk in the way Perl works: variable names
698     declared with C<my> are only visible in the I<next> statement. If the
699     whole C<< AnyEvent->io >> call, including the callback, would be done in
700     a single statement, the callback could not refer to the C<$read_watcher>
701     variable to undefine it, so it is done in two statements.
702    
703     Whether you'd want to format it like this is of course a matter of style,
704     this way emphasizes that the declaration and assignment really are one
705     logical statement.
706    
707 root 1.4 The callback itself calls C<sysread> for as many times as necessary, until
708 root 1.11 C<sysread> returns either an error or end-of-file:
709 root 1.4
710     cb => sub {
711     my $len = sysread $fh, $response, 1024, length $response;
712    
713     if ($len <= 0) {
714    
715     Note that C<sysread> has the ability to append data it reads to a scalar,
716 root 1.22 by specifying an offset, a feature of which we make good use of in this
717 root 1.11 example.
718 root 1.4
719     When C<sysread> indicates we are done, the callback C<undef>ines
720     the watcher and then C<send>'s the response data to the condition
721     variable. All this has the following effects:
722    
723     Undefining the watcher destroys it, as our callback was the only one still
724     having a reference to it. When the watcher gets destroyed, it destroys the
725     callback, which in turn means the C<$fh> handle is no longer used, so that
726     gets destroyed as well. The result is that all resources will be nicely
727     cleaned up by perl for us.
728    
729     =head3 Using the finger client
730    
731 root 1.5 Now, we could probably write the same finger client in a simpler way if
732     we used C<IO::Socket::INET>, ignored the problem of multiple hosts and
733     ignored IPv6 and a few other things that C<tcp_connect> handles for us.
734 root 1.4
735     But the main advantage is that we can not only run this finger function in
736     the background, we even can run multiple sessions in parallel, like this:
737    
738     my $f1 = finger "trouble", "noc.dfn.de"; # check for trouble tickets
739     my $f2 = finger "1736" , "noc.dfn.de"; # fetch ticket 1736
740 root 1.22 my $f3 = finger "hpa" , "kernel.org"; # finger hpa
741 root 1.4
742 root 1.22 print "trouble tickets:\n" , $f1->recv, "\n";
743 root 1.4 print "trouble ticket #1736:\n", $f2->recv, "\n";
744 root 1.22 print "kernel release info: " , $f3->recv, "\n";
745 root 1.4
746     It doesn't look like it, but in fact all three requests run in
747 root 1.9 parallel. The code waits for the first finger request to finish first, but
748 root 1.11 that doesn't keep it from executing them parallel: when the first C<recv>
749     call sees that the data isn't ready yet, it serves events for all three
750     requests automatically, until the first request has finished.
751    
752     The second C<recv> call might either find the data is already there, or it
753     will continue handling events until that is the case, and so on.
754 root 1.9
755     By taking advantage of network latencies, which allows us to serve other
756     requests and events while we wait for an event on one socket, the overall
757 root 1.11 time to do these three requests will be greatly reduced, typically all
758     three are done in the same time as the slowest of them would need to finish.
759 root 1.5
760     By the way, you do not actually have to wait in the C<recv> method on an
761 root 1.11 AnyEvent condition variable - after all, waiting is evil - you can also
762     register a callback:
763 root 1.5
764     $cv->cb (sub {
765     my $response = shift->recv;
766     # ...
767     });
768    
769     The callback will only be invoked when C<send> was called. In fact,
770     instead of returning a condition variable you could also pass a third
771     parameter to your finger function, the callback to invoke with the
772     response:
773    
774     sub finger($$$) {
775     my ($user, $host, $cb) = @_;
776    
777 root 1.11 How you implement it is a matter of taste - if you expect your function to
778     be used mainly in an event-based program you would normally prefer to pass
779     a callback directly. If you write a module and expect your users to use
780     it "synchronously" often (for example, a simple http-get script would not
781     really care much for events), then you would use a condition variable and
782 root 1.22 tell them "simply C<< ->recv >> the data".
783 root 1.4
784 root 1.11 =head3 Problems with the implementation and how to fix them
785 root 1.4
786     To make this example more real-world-ready, we would not only implement
787 root 1.22 some write buffering (for the paranoid, or maybe denial-of-service aware
788     security expert), but we would also have to handle timeouts and maybe
789     protocol errors.
790 root 1.4
791 root 1.11 Doing this quickly gets unwieldy, which is why we introduce
792     L<AnyEvent::Handle> in the next section, which takes care of all these
793     details for you and let's you concentrate on the actual protocol.
794    
795    
796     =head2 Implementing simple HTTP and HTTPS GET requests with AnyEvent::Handle
797    
798 root 1.22 The L<AnyEvent::Handle> module has been hyped quite a bit in this document
799     so far, so let's see what it really offers.
800 root 1.11
801     As finger is such a simple protocol, let's try something slightly more
802     complicated: HTTP/1.0.
803    
804     An HTTP GET request works by sending a single request line that indicates
805     what you want the server to do and the URI you want to act it on, followed
806     by as many "header" lines (C<Header: data>, same as e-mail headers) as
807     required for the request, ended by an empty line.
808    
809     The response is formatted very similarly, first a line with the response
810     status, then again as many header lines as required, then an empty line,
811     followed by any data that the server might send.
812    
813     Again, let's try it out with C<telnet> (I condensed the output a bit - if
814     you want to see the full response, do it yourself).
815    
816     # telnet www.google.com 80
817     Trying 209.85.135.99...
818     Connected to www.google.com (209.85.135.99).
819     Escape character is '^]'.
820     GET /test HTTP/1.0
821    
822     HTTP/1.0 404 Not Found
823     Date: Mon, 02 Jun 2008 07:05:54 GMT
824     Content-Type: text/html; charset=UTF-8
825    
826     <html><head>
827     [...]
828     Connection closed by foreign host.
829    
830     The C<GET ...> and the empty line were entered manually, the rest of the
831     telnet output is google's response, in which case a C<404 not found> one.
832    
833     So, here is how you would do it with C<AnyEvent::Handle>:
834    
835 root 1.12 sub http_get {
836     my ($host, $uri, $cb) = @_;
837    
838 root 1.24 # store results here
839     my ($response, $header, $body);
840    
841     my $handle; $handle = new AnyEvent::Handle
842     connect => [$host => 'http'],
843     on_error => sub {
844     $cb->("HTTP/1.0 500 $!");
845     $handle->destroy; # explicitly destroy handle
846     },
847     on_eof => sub {
848     $cb->($response, $header, $body);
849     $handle->destroy; # explicitly destroy handle
850     };
851 root 1.12
852 root 1.24 $handle->push_write ("GET $uri HTTP/1.0\015\012\015\012");
853 root 1.12
854 root 1.24 # now fetch response status line
855     $handle->push_read (line => sub {
856     my ($handle, $line) = @_;
857     $response = $line;
858     });
859 root 1.12
860 root 1.24 # then the headers
861     $handle->push_read (line => "\015\012\015\012", sub {
862     my ($handle, $line) = @_;
863     $header = $line;
864     });
865 root 1.12
866 root 1.24 # and finally handle any remaining data as body
867     $handle->on_read (sub {
868     $body .= $_[0]->rbuf;
869     $_[0]->rbuf = "";
870     });
871 root 1.12 }
872 root 1.11
873     And now let's go through it step by step. First, as usual, the overall
874     C<http_get> function structure:
875    
876     sub http_get {
877     my ($host, $uri, $cb) = @_;
878    
879 root 1.24 # store results here
880     my ($response, $header, $body);
881    
882     my $handle; $handle = new AnyEvent::Handle
883     ... create handle object
884    
885     ... push data to write
886    
887     ... push what to expect to read queue
888 root 1.11 }
889    
890     Unlike in the finger example, this time the caller has to pass a callback
891     to C<http_get>. Also, instead of passing a URL as one would expect, the
892     caller has to provide the hostname and URI - normally you would use the
893     C<URI> module to parse a URL and separate it into those parts, but that is
894     left to the inspired reader :)
895    
896     Since everything else is left to the caller, all C<http_get> does it to
897 root 1.24 initiate the connection by creating the AnyEvent::Handle object (which
898     calls C<tcp_connect> for us) and leave everything else to it's callback.
899    
900     The handle object is created, unsurprisingly, by calling the C<new>
901     method of L<AnyEvent::Handle>:
902 root 1.11
903 root 1.24 my $handle; $handle = new AnyEvent::Handle
904     connect => [$host => 'http'],
905     on_error => sub {
906     $cb->("HTTP/1.0 500 $!");
907     $handle->destroy; # explicitly destroy handle
908     },
909     on_eof => sub {
910     $cb->($response, $header, $body);
911     $handle->destroy; # explicitly destroy handle
912     };
913 root 1.11
914 root 1.24 The C<connect> argument tells AnyEvent::Handle to call C<tcp_connect> for
915     the specified host and service/port.
916 root 1.11
917 root 1.24 The C<on_error> callback will be called on any unexpected error, such as a
918     refused connection, or unexpected connection while reading the header.
919 root 1.11
920     Instead of having an extra mechanism to signal errors, connection errors
921     are signalled by crafting a special "response status line", like this:
922    
923     HTTP/1.0 500 Connection refused
924    
925     This means the caller cannot distinguish (easily) between
926     locally-generated errors and server errors, but it simplifies error
927     handling for the caller a lot.
928    
929 root 1.24 The error callback also destroys the handle explicitly, because we are not
930     interested in continuing after any errors. In AnyEvent::Handle callbacks
931     you have to call C<destroy> explicitly to destroy a handle. Outside of
932     those callbacks you cna just forget the object reference and it will be
933     automatically cleaned up.
934    
935     Last not least, we set an C<on_eof> callback that is called when the
936     other side indicates it has stopped writing data, which we will use to
937     gracefully shut down the handle and report the results. This callback is
938     only called when the read queue is empty - if the read queue expects some
939     data and the handle gets an EOF from the other side this will be an error
940     - after all, you did expect more to come.
941 root 1.11
942 root 1.24 If you wanted to write a server using AnyEvent::Handle, you would use
943     C<tcp_accept> and then create the AnyEvent::Handle with the C<fh>
944 root 1.11 argument.
945    
946     =head3 The write queue
947    
948     The next line sends the actual request:
949    
950 root 1.24 $handle->push_write ("GET $uri HTTP/1.0\015\012\015\012");
951 root 1.11
952     No headers will be sent (this is fine for simple requests), so the whole
953     request is just a single line followed by an empty line to signal the end
954     of the headers to the server.
955    
956     The more interesting question is why the method is called C<push_write>
957     and not just write. The reason is that you can I<always> add some write
958     data without blocking, and to do this, AnyEvent::Handle needs some write
959 root 1.22 queue internally - and C<push_write> simply pushes some data onto the end
960     of that queue, just like Perl's C<push> pushes data onto the end of an
961     array.
962 root 1.11
963     The deeper reason is that at some point in the future, there might
964     be C<unshift_write> as well, and in any case, we will shortly meet
965 root 1.22 C<push_read> and C<unshift_read>, and it's usually easiest to remember if
966 root 1.24 all those functions have some symmetry in their name. So C<push> is used
967     as the opposite of C<unshift> in AnyEvent::Handle, not as the opposite of
968     C<pull> - just like in Perl.
969    
970     Note that we call C<push_write> right after creating the AnyEvent::Handle
971     object, before it has had time to actually connect to the server. This is
972     fine, pushing the read and write requests will simply queue them in the
973     handle object until the connection has been established. Alternatively, we
974     could do this "on demand" in the C<on_connect> callback.
975 root 1.11
976     If C<push_write> is called with more than one argument, then you can even
977     do I<formatted> I/O, which simply means your data will be transformed in
978     some ways. For example, this would JSON-encode your data before pushing it
979     to the write queue:
980    
981     $handle->push_write (json => [1, 2, 3]);
982    
983     Apart from that, this pretty much summarises the write queue, there is
984     little else to it.
985    
986 root 1.22 Reading the response is far more interesting, because it involves the more
987     powerful and complex I<read queue>:
988 root 1.11
989     =head3 The read queue
990    
991 root 1.22 The response consists of three parts: a single line with the response
992     status, a single paragraph of headers ended by an empty line, and the
993     request body, which is simply the remaining data on that connection.
994 root 1.11
995     For the first two, we push two read requests onto the read queue:
996    
997 root 1.24 # now fetch response status line
998     $handle->push_read (line => sub {
999     my ($handle, $line) = @_;
1000     $response = $line;
1001     });
1002 root 1.11
1003 root 1.24 # then the headers
1004     $handle->push_read (line => "\015\012\015\012", sub {
1005     my ($handle, $line) = @_;
1006     $header = $line;
1007     });
1008 root 1.11
1009 root 1.22 While one can simply push a single callback to parse the data the
1010     queue, I<formatted> I/O really comes to our advantage here, as there
1011     is a ready-made "read line" read type. The first read expects a single
1012     line, ended by C<\015\012> (the standard end-of-line marker in internet
1013     protocols).
1014 root 1.11
1015     The second "line" is actually a single paragraph - instead of reading it
1016     line by line we tell C<push_read> that the end-of-line marker is really
1017     C<\015\012\015\012>, which is an empty line. The result is that the whole
1018     header paragraph will be treated as a single line and read. The word
1019     "line" is interpreted very freely, much like Perl itself does it.
1020    
1021     Note that push read requests are pushed immediately after creating the
1022     handle object - since AnyEvent::Handle provides a queue we can push as
1023     many requests as we want, and AnyEvent::Handle will handle them in order.
1024    
1025     There is, however, no read type for "the remaining data". For that, we
1026     install our own C<on_read> callback:
1027    
1028 root 1.24 # and finally handle any remaining data as body
1029     $handle->on_read (sub {
1030     $body .= $_[0]->rbuf;
1031     $_[0]->rbuf = "";
1032     });
1033 root 1.11
1034     This callback is invoked every time data arrives and the read queue is
1035     empty - which in this example will only be the case when both response and
1036 root 1.12 header have been read. The C<on_read> callback could actually have been
1037     specified when constructing the object, but doing it this way preserves
1038     logical ordering.
1039 root 1.1
1040 root 1.12 The read callback simply adds the current read buffer to it's C<$body>
1041 root 1.22 variable and, most importantly, I<empties> the buffer by assigning the
1042     empty string to it.
1043 root 1.1
1044 root 1.22 After AnyEvent::Handle has been so instructed, it will handle incoming
1045 root 1.12 data according to these instructions - if all goes well, the callback will
1046     be invoked with the response data, if not, it will get an error.
1047 root 1.1
1048 root 1.22 In general, you can implement pipelining (a semi-advanced feature of many
1049     protocols) very easy with AnyEvent::Handle: If you have a protocol with a
1050     request/response structure, your request methods/functions will all look
1051     like this (simplified):
1052 root 1.13
1053     sub request {
1054    
1055     # send the request to the server
1056     $handle->push_write (...);
1057    
1058     # push some response handlers
1059     $handle->push_read (...);
1060     }
1061    
1062 root 1.22 This means you can queue as many requests as you want, and while
1063     AnyEvent::Handle goes through its read queue to handle the response data,
1064     the other side can work on the next request - queueing the request just
1065     appends some data to the write queue and installs a handler to be called
1066     later.
1067    
1068     You might ask yourself how to handle decisions you can only make I<after>
1069     you have received some data (such as handling a short error response or a
1070     long and differently-formatted response). The answer to this problem is
1071     C<unshift_read>, which we will introduce together with an example in the
1072     coming sections.
1073 root 1.1
1074 root 1.22 =head3 Using C<http_get>
1075    
1076     Finally, here is how you would use C<http_get>:
1077 root 1.1
1078 root 1.12 http_get "www.google.com", "/", sub {
1079     my ($response, $header, $body) = @_;
1080 root 1.1
1081 root 1.12 print
1082     $response, "\n",
1083     $body;
1084     };
1085 root 1.1
1086 root 1.12 And of course, you can run as many of these requests in parallel as you
1087     want (and your memory supports).
1088 root 1.1
1089 root 1.13 =head3 HTTPS
1090    
1091     Now, as promised, let's implement the same thing for HTTPS, or more
1092     correctly, let's change our C<http_get> function into a function that
1093     speaks HTTPS instead.
1094    
1095     HTTPS is, quite simply, a standard TLS connection (B<T>ransport B<L>ayer
1096     B<S>ecurity is the official name for what most people refer to as C<SSL>)
1097 root 1.22 that contains standard HTTP protocol exchanges. The only other difference
1098     to HTTP is that by default it uses port C<443> instead of port C<80>.
1099 root 1.13
1100 root 1.22 To implement these two differences we need two tiny changes, first, in the
1101 root 1.24 C<connect> parameter, we replace C<http> by C<https> to connect to the
1102     https port:
1103 root 1.13
1104 root 1.24 connect => [$host => 'https'],
1105 root 1.13
1106     The other change deals with TLS, which is something L<AnyEvent::Handle>
1107 root 1.22 does for us, as long as I<you> made sure that the L<Net::SSLeay> module
1108     is around. To enable TLS with L<AnyEvent::Handle>, we simply pass an
1109     additional C<tls> parameter to the call to C<AnyEvent::Handle::new>:
1110 root 1.13
1111     tls => "connect",
1112    
1113     Specifying C<tls> enables TLS, and the argument specifies whether
1114     AnyEvent::Handle is the server side ("accept") or the client side
1115     ("connect") for the TLS connection, as unlike TCP, there is a clear
1116     server/client relationship in TLS.
1117    
1118 root 1.14 That's all.
1119    
1120 root 1.22 Of course, all this should be handled transparently by C<http_get>
1121     after parsing the URL. If you need this, see the part about exercising
1122     your inspiration earlier in this document. You could also use the
1123     L<AnyEvent::HTTP> module from CPAN, which implements all this and works
1124     around a lot of quirks for you, too.
1125 root 1.13
1126 root 1.12 =head3 The read queue - revisited
1127 root 1.1
1128 root 1.13 HTTP always uses the same structure in its responses, but many protocols
1129 root 1.22 require parsing responses differently depending on the response itself.
1130 root 1.13
1131     For example, in SMTP, you normally get a single response line:
1132    
1133     220 mail.example.net Neverusesendmail 8.8.8 <mailme@example.net>
1134    
1135     But SMTP also supports multi-line responses:
1136    
1137     220-mail.example.net Neverusesendmail 8.8.8 <mailme@example.net>
1138     220-hey guys
1139     220 my response is longer than yours
1140    
1141     To handle this, we need C<unshift_read>. As the name (hopefully) implies,
1142 root 1.22 C<unshift_read> will not append your read request to the end of the read
1143 root 1.13 queue, but instead it will prepend it to the queue.
1144    
1145 root 1.22 This is useful in the situation above: Just push your response-line read
1146 root 1.13 request when sending the SMTP command, and when handling it, you look at
1147 root 1.22 the line to see if more is to come, and C<unshift_read> another reader
1148     callback if required, like this:
1149 root 1.13
1150     my $response; # response lines end up in here
1151    
1152     my $read_response; $read_response = sub {
1153     my ($handle, $line) = @_;
1154    
1155     $response .= "$line\n";
1156    
1157     # check for continuation lines ("-" as 4th character")
1158     if ($line =~ /^...-/) {
1159     # if yes, then unshift another line read
1160     $handle->unshift_read (line => $read_response);
1161    
1162     } else {
1163     # otherwise we are done
1164    
1165     # free callback
1166     undef $read_response;
1167    
1168     print "we are don reading: $response\n";
1169     }
1170     };
1171    
1172     $handle->push_read (line => $read_response);
1173 root 1.1
1174 root 1.13 This recipe can be used for all similar parsing problems, for example in
1175     NNTP, the response code to some commands indicates that more data will be
1176 root 1.14 sent:
1177    
1178     $handle->push_write ("article 42");
1179    
1180     # read response line
1181     $handle->push_read (line => sub {
1182     my ($handle, $status) = @_;
1183    
1184     # article data following?
1185     if ($status =~ /^2/) {
1186     # yes, read article body
1187    
1188     $handle->unshift_read (line => "\012.\015\012", sub {
1189     my ($handle, $body) = @_;
1190    
1191     $finish->($status, $body);
1192     });
1193    
1194     } else {
1195     # some error occured, no article data
1196    
1197     $finish->($status);
1198     }
1199     }
1200    
1201     =head3 Your own read queue handler
1202    
1203     Sometimes, your protocol doesn't play nice and uses lines or chunks of
1204 root 1.22 data not formatted in a way handled by AnyEvent::Handle out of the box. In
1205     this case you have to implement your own read parser.
1206 root 1.14
1207     To make up a contorted example, imagine you are looking for an even
1208     number of characters followed by a colon (":"). Also imagine that
1209     AnyEvent::Handle had no C<regex> read type which could be used, so you'd
1210     had to do it manually.
1211    
1212 root 1.22 To implement a read handler for this, you would C<push_read> (or
1213     C<unshift_read>) just a single code reference.
1214 root 1.14
1215     This code reference will then be called each time there is (new) data
1216 root 1.22 available in the read buffer, and is expected to either successfully
1217     eat/consume some of that data (and return true) or to return false to
1218     indicate that it wants to be called again.
1219    
1220     If the code reference returns true, then it will be removed from the
1221     read queue (because it has parsed/consumed whatever it was supposed to
1222     consume), otherwise it stays in the front of it.
1223 root 1.14
1224     The example above could be coded like this:
1225    
1226     $handle->push_read (sub {
1227     my ($handle) = @_;
1228    
1229     # check for even number of characters + ":"
1230     # and remove the data if a match is found.
1231     # if not, return false (actually nothing)
1232    
1233     $handle->{rbuf} =~ s/^( (?:..)* ) ://x
1234     or return;
1235    
1236     # we got some data in $1, pass it to whoever wants it
1237     $finish->($1);
1238    
1239     # and return true to indicate we are done
1240     1
1241     });
1242    
1243 root 1.22 This concludes our little tutorial.
1244    
1245     =head1 Where to go from here?
1246    
1247 root 1.23 This introduction should have explained the key concepts of L<AnyEvent>
1248     - event watchers and condition variables, L<AnyEvent::Socket> - basic
1249     networking utilities, and L<AnyEvent::Handle> - a nice wrapper around
1250     handles.
1251 root 1.22
1252     You could either start coding stuff right away, look at those manual
1253     pages for the gory details, or roam CPAN for other AnyEvent modules (such
1254     as L<AnyEvent::IRC> or L<AnyEvent::HTTP>) to see more code examples (or
1255     simply to use them).
1256    
1257     If you need a protocol that doesn't have an implementation using AnyEvent,
1258     remember that you can mix AnyEvent with one other event framework, such as
1259     L<POE>, so you can always use AnyEvent for your own tasks plus modules of
1260     one other event framework to fill any gaps.
1261    
1262     And last not least, you could also look at L<Coro>, especially
1263     L<Coro::AnyEvent>, to see how you can turn event-based programming from
1264     callback style back to the usual imperative style (also called "inversion
1265     of control" - AnyEvent calls I<you>, but Coro lets I<you> call AnyEvent).
1266 root 1.1
1267 root 1.15 =head1 Authors
1268 root 1.6
1269     Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.
1270