Section: User Contributed Perl Documentation (3)
Updated: 2008-05-01
Index Return to Main Contents


AnyEvent::Handle - non-blocking I/O on filehandles via AnyEvent  


   use AnyEvent;
   use AnyEvent::Handle;

   my $cv = AnyEvent->condvar;

   my $ae_fh = AnyEvent::Handle->new (fh => \*STDIN);


   # or use the constructor to pass the callback:

   my $ae_fh2 =
      AnyEvent::Handle->new (
         fh => \*STDIN,
         on_eof => sub {




This module is a helper module to make it easier to do event-based I/O on filehandles (and sockets, see AnyEvent::Socket for an easy way to make non-blocking resolves and connects).

In the following, when the documentation refers to of ``bytes'' then this means characters. As sysread and syswrite are used for all I/O, their treatment of characters applies to this module as well.

All callbacks will be invoked with the handle object as their first argument.  


new (%args)
The constructor supports these arguments (all as key => value pairs).
fh => $filehandle [MANDATORY]
The filehandle this AnyEvent::Handle object will operate on.

NOTE: The filehandle will be set to non-blocking (using AnyEvent::Util::fh_nonblocking).

on_eof => $cb->($self) [MANDATORY]
Set the callback to be called on EOF.
on_error => $cb->($self)
This is the fatal error callback, that is called when, well, a fatal error ocurs, such as not being able to resolve the hostname, failure to connect or a read error.

The object will not be in a usable state when this callback has been called.

On callback entrance, the value of $! contains the operating system error (or "ENOSPC" or "EPIPE").

While not mandatory, it is highly recommended to set this callback, as you will not be notified of errors otherwise. The default simply calls die.

on_read => $cb->($self)
This sets the default read callback, which is called when data arrives and no read request is in the queue.

To access (and remove data from) the read buffer, use the "->rbuf" method or acces sthe "$self-"{rbuf}> member directly.

When an EOF condition is detected then AnyEvent::Handle will first try to feed all the remaining data to the queued callbacks and "on_read" before calling the "on_eof" callback. If no progress can be made, then a fatal error will be raised (with $! set to "EPIPE").

on_drain => $cb->()
This sets the callback that is called when the write buffer becomes empty (or when the callback is set and the buffer is empty already).

To append to the write buffer, use the "->push_write" method.

rbuf_max => <bytes>
If defined, then a fatal error will be raised (with $! set to "ENOSPC") when the read buffer ever (strictly) exceeds this size. This is useful to avoid denial-of-service attacks.

For example, a server accepting connections from untrusted sources should be configured to accept only so-and-so much data that it cannot act on (for example, when expecting a line, an attacker could send an unlimited amount of data without a callback ever being called as long as the line isn't finished).

read_size => <bytes>
The default read block size (the amount of bytes this module will try to read on each [loop iteration). Default: 4096.
low_water_mark => <bytes>
Sets the amount of bytes (default: 0) that make up an ``empty'' write buffer: If the write reaches this size or gets even samller it is considered empty.
$fh = $handle->fh
This method returns the filehandle of the AnyEvent::Handle object.
$handle->on_error ($cb)
Replace the current "on_error" callback (see the "on_error" constructor argument).
$handle->on_eof ($cb)
Replace the current "on_eof" callback (see the "on_eof" constructor argument).


AnyEvent::Handle manages two queues per handle, one for writing and one for reading.

The write queue is very simple: you can add data to its end, and AnyEvent::Handle will automatically try to get rid of it for you.

When data could be writtena nd the write buffer is shorter then the low water mark, the "on_drain" callback will be invoked.

$handle->on_drain ($cb)
Sets the "on_drain" callback or clears it (see the description of "on_drain" in the constructor).
$handle->push_write ($data)
Queues the given scalar to be written. You can push as much data as you want (only limited by the available memory), as "AnyEvent::Handle" buffers it independently of the kernel.


AnyEvent::Handle manages two queues per handle, one for writing and one for reading.

The read queue is more complex than the write queue. It can be used in two ways, the ``simple'' way, using only "on_read" and the ``complex'' way, using a queue.

In the simple case, you just install an "on_read" callback and whenever new data arrives, it will be called. You can then remove some data (if enough is there) from the read buffer ("$handle->rbuf") if you want or not.

In the more complex case, you want to queue multiple callbacks. In this case, AnyEvent::Handle will call the first queued callback each time new data arrives and removes it when it has done its job (see "push_read", below).

This way you can, for example, push three line-reads, followed by reading a chunk of data, and AnyEvent::Handle will execute them in order.

Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by the specified number of bytes which give an XML datagram.

   # in the default state, expect some header bytes
   $handle->on_read (sub {
      # some data is here, now queue the length-header-read (4 octets)
      shift->unshift_read_chunk (4, sub {
         # header arrived, decode
         my $len = unpack "N", $_[1];

         # now read the payload
         shift->unshift_read_chunk ($len, sub {
            my $xml = $_[1];
            # handle xml

Example 2: Implement a client for a protocol that replies either with ``OK'' and another line or ``ERROR'' for one request, and 64 bytes for the second request. Due tot he availability of a full queue, we can just pipeline sending both requests and manipulate the queue as necessary in the callbacks:

   # request one
   $handle->push_write ("request 1\015\012");

   # we expect "ERROR" or "OK" as response, so push a line read
   $handle->push_read_line (sub {
      # if we got an "OK", we have to _prepend_ another line,
      # so it will be read before the second request reads its 64 bytes
      # which are already in the queue when this callback is called
      # we don't do this in case we got an error
      if ($_[1] eq "OK") {
         $_[0]->unshift_read_line (sub {
            my $response = $_[1];

   # request two
   $handle->push_write ("request 2\015\012");

   # simply read 64 bytes, always
   $handle->push_read_chunk (64, sub {
      my $response = $_[1];

$handle->on_read ($cb)
This replaces the currently set "on_read" callback, or clears it (when the new callback is "undef"). See the description of "on_read" in the constructor.
Returns the read buffer (as a modifiable lvalue).

You can access the read buffer directly as the "->{rbuf}" member, if you want.

NOTE: The read buffer should only be used or modified if the "on_read", "push_read" or "unshift_read" methods are used. The other read methods automatically manage the read buffer.

$handle->push_read ($cb)
$handle->unshift_read ($cb)
Append the given callback to the end of the queue ("push_read") or prepend it ("unshift_read").

The callback is called each time some additional read data arrives.

It must check wether enough data is in the read buffer already.

If not enough data is available, it must return the empty list or a false value, in which case it will be called repeatedly until enough data is available (or an error condition is detected).

If enough data was available, then the callback must remove all data it is interested in (which can be none at all) and return a true value. After returning true, it will be removed from the queue.

$handle->push_read_chunk ($len, $cb->($self, $data))
$handle->unshift_read_chunk ($len, $cb->($self, $data))
Append the given callback to the end of the queue ("push_read_chunk") or prepend it ("unshift_read_chunk").

The callback will be called only once $len bytes have been read, and these $len bytes will be passed to the callback.

$handle->push_read_line ([$eol, ]$cb->($self, $line, $eol))
$handle->unshift_read_line ([$eol, ]$cb->($self, $line, $eol))
Append the given callback to the end of the queue ("push_read_line") or prepend it ("unshift_read_line").

The callback will be called only once a full line (including the end of line marker, $eol) has been read. This line (excluding the end of line marker) will be passed to the callback as second argument ($line), and the end of line marker as the third argument ($eol).

The end of line marker, $eol, can be either a string, in which case it will be interpreted as a fixed record end marker, or it can be a regex object (e.g. created by "qr"), in which case it is interpreted as a regular expression.

The end of line marker argument $eol is optional, if it is missing (NOT undef), then "qr|\015?\012|" is used (which is good for most internet protocols).

Partial lines at the end of the stream will never be returned, as they are not marked by the end of line marker.

In rare cases you actually do not want to read anything form the socket. In this case you can call "stop_read". Neither "on_read" no any queued callbacks will be executed then. To start readign again, call "start_read".


Robin Redeker "<elmex at>", Marc Lehmann <>.



AUTHOR manual pages