1AnyEvent::Handle(3)   User Contributed Perl Documentation  AnyEvent::Handle(3)
2
3
4

NAME

6       AnyEvent::Handle - non-blocking I/O on streaming handles via AnyEvent
7

SYNOPSIS

9          use AnyEvent;
10          use AnyEvent::Handle;
11
12          my $cv = AnyEvent->condvar;
13
14          my $hdl; $hdl = new AnyEvent::Handle
15             fh => \*STDIN,
16             on_error => sub {
17                my ($hdl, $fatal, $msg) = @_;
18                warn "got error $msg\n";
19                $hdl->destroy;
20                $cv->send;
21             };
22
23          # send some request line
24          $hdl->push_write ("getinfo\015\012");
25
26          # read the response line
27          $hdl->push_read (line => sub {
28             my ($hdl, $line) = @_;
29             warn "got line <$line>\n";
30             $cv->send;
31          });
32
33          $cv->recv;
34

DESCRIPTION

36       This module is a helper module to make it easier to do event-based I/O
37       on stream-based filehandles (sockets, pipes or other stream things).
38
39       The AnyEvent::Intro tutorial contains some well-documented
40       AnyEvent::Handle examples.
41
42       In the following, when the documentation refers to of "bytes" then this
43       means characters. As sysread and syswrite are used for all I/O, their
44       treatment of characters applies to this module as well.
45
46       At the very minimum, you should specify "fh" or "connect", and the
47       "on_error" callback.
48
49       All callbacks will be invoked with the handle object as their first
50       argument.
51

METHODS

53       $handle = new AnyEvent::Handle fh => $filehandle, key => value...
54           The constructor supports these arguments (all as "key => value"
55           pairs).
56
57           fh => $filehandle     ["fh" or "connect" MANDATORY]
58               The filehandle this AnyEvent::Handle object will operate on.
59               NOTE: The filehandle will be set to non-blocking mode (using
60               "AnyEvent::Util::fh_nonblocking") by the constructor and needs
61               to stay in that mode.
62
63           connect => [$host, $service]      ["fh" or "connect" MANDATORY]
64               Try to connect to the specified host and service (port), using
65               "AnyEvent::Socket::tcp_connect". The $host additionally becomes
66               the default "peername".
67
68               You have to specify either this parameter, or "fh", above.
69
70               It is possible to push requests on the read and write queues,
71               and modify properties of the stream, even while
72               AnyEvent::Handle is connecting.
73
74               When this parameter is specified, then the "on_prepare",
75               "on_connect_error" and "on_connect" callbacks will be called
76               under the appropriate circumstances:
77
78               on_prepare => $cb->($handle)
79                   This (rarely used) callback is called before a new
80                   connection is attempted, but after the file handle has been
81                   created. It could be used to prepare the file handle with
82                   parameters required for the actual connect (as opposed to
83                   settings that can be changed when the connection is already
84                   established).
85
86                   The return value of this callback should be the connect
87                   timeout value in seconds (or 0, or "undef", or the empty
88                   list, to indicate the default timeout is to be used).
89
90               on_connect => $cb->($handle, $host, $port, $retry->())
91                   This callback is called when a connection has been
92                   successfully established.
93
94                   The actual numeric host and port (the socket peername) are
95                   passed as parameters, together with a retry callback.
96
97                   When, for some reason, the handle is not acceptable, then
98                   calling $retry will continue with the next connection
99                   target (in case of multi-homed hosts or SRV records there
100                   can be multiple connection endpoints). At the time it is
101                   called the read and write queues, eof status, tls status
102                   and similar properties of the handle will have been reset.
103
104                   In most cases, ignoring the $retry parameter is the way to
105                   go.
106
107               on_connect_error => $cb->($handle, $message)
108                   This callback is called when the connection could not be
109                   established. $! will contain the relevant error code, and
110                   $message a message describing it (usually the same as
111                   "$!").
112
113                   If this callback isn't specified, then "on_error" will be
114                   called with a fatal error instead.
115
116           on_error => $cb->($handle, $fatal, $message)
117               This is the error callback, which is called when, well, some
118               error occured, such as not being able to resolve the hostname,
119               failure to connect or a read error.
120
121               Some errors are fatal (which is indicated by $fatal being
122               true). On fatal errors the handle object will be destroyed (by
123               a call to "-> destroy") after invoking the error callback
124               (which means you are free to examine the handle object).
125               Examples of fatal errors are an EOF condition with active (but
126               unsatisifable) read watchers ("EPIPE") or I/O errors. In cases
127               where the other side can close the connection at their will it
128               is often easiest to not report "EPIPE" errors in this callback.
129
130               AnyEvent::Handle tries to find an appropriate error code for
131               you to check against, but in some cases (TLS errors), this does
132               not work well. It is recommended to always output the $message
133               argument in human-readable error messages (it's usually the
134               same as "$!").
135
136               Non-fatal errors can be retried by simply returning, but it is
137               recommended to simply ignore this parameter and instead abondon
138               the handle object when this callback is invoked. Examples of
139               non-fatal errors are timeouts "ETIMEDOUT") or badly-formatted
140               data ("EBADMSG").
141
142               On callback entrance, the value of $! contains the operating
143               system error code (or "ENOSPC", "EPIPE", "ETIMEDOUT", "EBADMSG"
144               or "EPROTO").
145
146               While not mandatory, it is highly recommended to set this
147               callback, as you will not be notified of errors otherwise. The
148               default simply calls "croak".
149
150           on_read => $cb->($handle)
151               This sets the default read callback, which is called when data
152               arrives and no read request is in the queue (unlike read queue
153               callbacks, this callback will only be called when at least one
154               octet of data is in the read buffer).
155
156               To access (and remove data from) the read buffer, use the
157               "->rbuf" method or access the "$handle->{rbuf}" member
158               directly. Note that you must not enlarge or modify the read
159               buffer, you can only remove data at the beginning from it.
160
161               When an EOF condition is detected then AnyEvent::Handle will
162               first try to feed all the remaining data to the queued
163               callbacks and "on_read" before calling the "on_eof" callback.
164               If no progress can be made, then a fatal error will be raised
165               (with $! set to "EPIPE").
166
167               Note that, unlike requests in the read queue, an "on_read"
168               callback doesn't mean you require some data: if there is an EOF
169               and there are outstanding read requests then an error will be
170               flagged. With an "on_read" callback, the "on_eof" callback will
171               be invoked.
172
173           on_eof => $cb->($handle)
174               Set the callback to be called when an end-of-file condition is
175               detected, i.e. in the case of a socket, when the other side has
176               closed the connection cleanly, and there are no outstanding
177               read requests in the queue (if there are read requests, then an
178               EOF counts as an unexpected connection close and will be
179               flagged as an error).
180
181               For sockets, this just means that the other side has stopped
182               sending data, you can still try to write data, and, in fact,
183               one can return from the EOF callback and continue writing data,
184               as only the read part has been shut down.
185
186               If an EOF condition has been detected but no "on_eof" callback
187               has been set, then a fatal error will be raised with $! set to
188               <0>.
189
190           on_drain => $cb->($handle)
191               This sets the callback that is called when the write buffer
192               becomes empty (or when the callback is set and the buffer is
193               empty already).
194
195               To append to the write buffer, use the "->push_write" method.
196
197               This callback is useful when you don't want to put all of your
198               write data into the queue at once, for example, when you want
199               to write the contents of some file to the socket you might not
200               want to read the whole file into memory and push it into the
201               queue, but instead only read more data from the file when the
202               write queue becomes empty.
203
204           timeout => $fractional_seconds
205           rtimeout => $fractional_seconds
206           wtimeout => $fractional_seconds
207               If non-zero, then these enables an "inactivity" timeout:
208               whenever this many seconds pass without a successful read or
209               write on the underlying file handle (or a call to
210               "timeout_reset"), the "on_timeout" callback will be invoked
211               (and if that one is missing, a non-fatal "ETIMEDOUT" error will
212               be raised).
213
214               There are three variants of the timeouts that work fully
215               independent of each other, for both read and write, just read,
216               and just write: "timeout", "rtimeout" and "wtimeout", with
217               corresponding callbacks "on_timeout", "on_rtimeout" and
218               "on_wtimeout", and reset functions "timeout_reset",
219               "rtimeout_reset", and "wtimeout_reset".
220
221               Note that timeout processing is also active when you currently
222               do not have any outstanding read or write requests: If you plan
223               to keep the connection idle then you should disable the timout
224               temporarily or ignore the timeout in the "on_timeout" callback,
225               in which case AnyEvent::Handle will simply restart the timeout.
226
227               Zero (the default) disables this timeout.
228
229           on_timeout => $cb->($handle)
230               Called whenever the inactivity timeout passes. If you return
231               from this callback, then the timeout will be reset as if some
232               activity had happened, so this condition is not fatal in any
233               way.
234
235           rbuf_max => <bytes>
236               If defined, then a fatal error will be raised (with $! set to
237               "ENOSPC") when the read buffer ever (strictly) exceeds this
238               size. This is useful to avoid some forms of denial-of-service
239               attacks.
240
241               For example, a server accepting connections from untrusted
242               sources should be configured to accept only so-and-so much data
243               that it cannot act on (for example, when expecting a line, an
244               attacker could send an unlimited amount of data without a
245               callback ever being called as long as the line isn't finished).
246
247           autocork => <boolean>
248               When disabled (the default), then "push_write" will try to
249               immediately write the data to the handle, if possible. This
250               avoids having to register a write watcher and wait for the next
251               event loop iteration, but can be inefficient if you write
252               multiple small chunks (on the wire, this disadvantage is
253               usually avoided by your kernel's nagle algorithm, see
254               "no_delay", but this option can save costly syscalls).
255
256               When enabled, then writes will always be queued till the next
257               event loop iteration. This is efficient when you do many small
258               writes per iteration, but less efficient when you do a single
259               write only per iteration (or when the write buffer often is
260               full). It also increases write latency.
261
262           no_delay => <boolean>
263               When doing small writes on sockets, your operating system
264               kernel might wait a bit for more data before actually sending
265               it out. This is called the Nagle algorithm, and usually it is
266               beneficial.
267
268               In some situations you want as low a delay as possible, which
269               can be accomplishd by setting this option to a true value.
270
271               The default is your opertaing system's default behaviour (most
272               likely enabled), this option explicitly enables or disables it,
273               if possible.
274
275           keepalive => <boolean>
276               Enables (default disable) the SO_KEEPALIVE option on the stream
277               socket: normally, TCP connections have no time-out once
278               established, so TCP connections, once established, can stay
279               alive forever even when the other side has long gone. TCP
280               keepalives are a cheap way to take down long-lived TCP
281               connections whent he other side becomes unreachable. While the
282               default is OS-dependent, TCP keepalives usually kick in after
283               around two hours, and, if the other side doesn't reply, take
284               down the TCP connection some 10 to 15 minutes later.
285
286               It is harmless to specify this option for file handles that do
287               not support keepalives, and enabling it on connections that are
288               potentially long-lived is usually a good idea.
289
290           oobinline => <boolean>
291               BSD majorly fucked up the implementation of TCP urgent data.
292               The result is that almost no OS implements TCP according to the
293               specs, and every OS implements it slightly differently.
294
295               If you want to handle TCP urgent data, then setting this flag
296               (the default is enabled) gives you the most portable way of
297               getting urgent data, by putting it into the stream.
298
299               Since BSD emulation of OOB data on top of TCP's urgent data can
300               have security implications, AnyEvent::Handle sets this flag
301               automatically unless explicitly specified. Note that setting
302               this flag after establishing a connection may be a bit too late
303               (data loss could already have occured on BSD systems), but at
304               least it will protect you from most attacks.
305
306           read_size => <bytes>
307               The default read block size (the amount of bytes this module
308               will try to read during each loop iteration, which affects
309               memory requirements). Default: 8192.
310
311           low_water_mark => <bytes>
312               Sets the amount of bytes (default: 0) that make up an "empty"
313               write buffer: If the write reaches this size or gets even
314               samller it is considered empty.
315
316               Sometimes it can be beneficial (for performance reasons) to add
317               data to the write buffer before it is fully drained, but this
318               is a rare case, as the operating system kernel usually buffers
319               data as well, so the default is good in almost all cases.
320
321           linger => <seconds>
322               If non-zero (default: 3600), then the destructor of the
323               AnyEvent::Handle object will check whether there is still
324               outstanding write data and will install a watcher that will
325               write this data to the socket. No errors will be reported (this
326               mostly matches how the operating system treats outstanding data
327               at socket close time).
328
329               This will not work for partial TLS data that could not be
330               encoded yet. This data will be lost. Calling the "stoptls"
331               method in time might help.
332
333           peername => $string
334               A string used to identify the remote site - usually the DNS
335               hostname (not IDN!) used to create the connection, rarely the
336               IP address.
337
338               Apart from being useful in error messages, this string is also
339               used in TLS peername verification (see "verify_peername" in
340               AnyEvent::TLS). This verification will be skipped when
341               "peername" is not specified or "undef".
342
343           tls => "accept" | "connect" | Net::SSLeay::SSL object
344               When this parameter is given, it enables TLS (SSL) mode, that
345               means AnyEvent will start a TLS handshake as soon as the
346               connection has been established and will transparently
347               encrypt/decrypt data afterwards.
348
349               All TLS protocol errors will be signalled as "EPROTO", with an
350               appropriate error message.
351
352               TLS mode requires Net::SSLeay to be installed (it will be
353               loaded automatically when you try to create a TLS handle): this
354               module doesn't have a dependency on that module, so if your
355               module requires it, you have to add the dependency yourself.
356
357               Unlike TCP, TLS has a server and client side: for the TLS
358               server side, use "accept", and for the TLS client side of a
359               connection, use "connect" mode.
360
361               You can also provide your own TLS connection object, but you
362               have to make sure that you call either
363               "Net::SSLeay::set_connect_state" or
364               "Net::SSLeay::set_accept_state" on it before you pass it to
365               AnyEvent::Handle. Also, this module will take ownership of this
366               connection object.
367
368               At some future point, AnyEvent::Handle might switch to another
369               TLS implementation, then the option to use your own session
370               object will go away.
371
372               IMPORTANT: since Net::SSLeay "objects" are really only
373               integers, passing in the wrong integer will lead to certain
374               crash. This most often happens when one uses a stylish "tls =>
375               1" and is surprised about the segmentation fault.
376
377               See the "->starttls" method for when need to start TLS
378               negotiation later.
379
380           tls_ctx => $anyevent_tls
381               Use the given "AnyEvent::TLS" object to create the new TLS
382               connection (unless a connection object was specified directly).
383               If this parameter is missing, then AnyEvent::Handle will use
384               "AnyEvent::Handle::TLS_CTX".
385
386               Instead of an object, you can also specify a hash reference
387               with "key => value" pairs. Those will be passed to
388               AnyEvent::TLS to create a new TLS context object.
389
390           on_starttls => $cb->($handle, $success[, $error_message])
391               This callback will be invoked when the TLS/SSL handshake has
392               finished. If $success is true, then the TLS handshake
393               succeeded, otherwise it failed ("on_stoptls" will not be called
394               in this case).
395
396               The session in "$handle->{tls}" can still be examined in this
397               callback, even when the handshake was not successful.
398
399               TLS handshake failures will not cause "on_error" to be invoked
400               when this callback is in effect, instead, the error message
401               will be passed to "on_starttls".
402
403               Without this callback, handshake failures lead to "on_error"
404               being called, as normal.
405
406               Note that you cannot call "starttls" right again in this
407               callback. If you need to do that, start an zero-second timer
408               instead whose callback can then call "->starttls" again.
409
410           on_stoptls => $cb->($handle)
411               When a SSLv3/TLS shutdown/close notify/EOF is detected and this
412               callback is set, then it will be invoked after freeing the TLS
413               session. If it is not, then a TLS shutdown condition will be
414               treated like a normal EOF condition on the handle.
415
416               The session in "$handle->{tls}" can still be examined in this
417               callback.
418
419               This callback will only be called on TLS shutdowns, not when
420               the underlying handle signals EOF.
421
422           json => JSON or JSON::XS object
423               This is the json coder object used by the "json" read and write
424               types.
425
426               If you don't supply it, then AnyEvent::Handle will create and
427               use a suitable one (on demand), which will write and expect
428               UTF-8 encoded JSON texts.
429
430               Note that you are responsible to depend on the JSON module if
431               you want to use this functionality, as AnyEvent does not have a
432               dependency itself.
433
434       $fh = $handle->fh
435           This method returns the file handle used to create the
436           AnyEvent::Handle object.
437
438       $handle->on_error ($cb)
439           Replace the current "on_error" callback (see the "on_error"
440           constructor argument).
441
442       $handle->on_eof ($cb)
443           Replace the current "on_eof" callback (see the "on_eof" constructor
444           argument).
445
446       $handle->on_timeout ($cb)
447       $handle->on_rtimeout ($cb)
448       $handle->on_wtimeout ($cb)
449           Replace the current "on_timeout", "on_rtimeout" or "on_wtimeout"
450           callback, or disables the callback (but not the timeout) if $cb =
451           "undef". See the "timeout" constructor argument and method.
452
453       $handle->autocork ($boolean)
454           Enables or disables the current autocork behaviour (see "autocork"
455           constructor argument). Changes will only take effect on the next
456           write.
457
458       $handle->no_delay ($boolean)
459           Enables or disables the "no_delay" setting (see constructor
460           argument of the same name for details).
461
462       $handle->keepalive ($boolean)
463           Enables or disables the "keepalive" setting (see constructor
464           argument of the same name for details).
465
466       $handle->oobinline ($boolean)
467           Enables or disables the "oobinline" setting (see constructor
468           argument of the same name for details).
469
470       $handle->keepalive ($boolean)
471           Enables or disables the "keepalive" setting (see constructor
472           argument of the same name for details).
473
474       $handle->on_starttls ($cb)
475           Replace the current "on_starttls" callback (see the "on_starttls"
476           constructor argument).
477
478       $handle->on_stoptls ($cb)
479           Replace the current "on_stoptls" callback (see the "on_stoptls"
480           constructor argument).
481
482       $handle->rbuf_max ($max_octets)
483           Configures the "rbuf_max" setting ("undef" disables it).
484
485       $handle->timeout ($seconds)
486       $handle->rtimeout ($seconds)
487       $handle->wtimeout ($seconds)
488           Configures (or disables) the inactivity timeout.
489
490       $handle->timeout_reset
491       $handle->rtimeout_reset
492       $handle->wtimeout_reset
493           Reset the activity timeout, as if data was received or sent.
494
495           These methods are cheap to call.
496
497   WRITE QUEUE
498       AnyEvent::Handle manages two queues per handle, one for writing and one
499       for reading.
500
501       The write queue is very simple: you can add data to its end, and
502       AnyEvent::Handle will automatically try to get rid of it for you.
503
504       When data could be written and the write buffer is shorter then the low
505       water mark, the "on_drain" callback will be invoked.
506
507       $handle->on_drain ($cb)
508           Sets the "on_drain" callback or clears it (see the description of
509           "on_drain" in the constructor).
510
511           This method may invoke callbacks (and therefore the handle might be
512           destroyed after it returns).
513
514       $handle->push_write ($data)
515           Queues the given scalar to be written. You can push as much data as
516           you want (only limited by the available memory), as
517           "AnyEvent::Handle" buffers it independently of the kernel.
518
519           This method may invoke callbacks (and therefore the handle might be
520           destroyed after it returns).
521
522       $handle->push_write (type => @args)
523           Instead of formatting your data yourself, you can also let this
524           module do the job by specifying a type and type-specific arguments.
525           You can also specify the (fully qualified) name of a package, in
526           which case AnyEvent tries to load the package and then expects to
527           find the "anyevent_read_type" function inside (see "custom write
528           types", below).
529
530           Predefined types are (if you have ideas for additional types, feel
531           free to drop by and tell us):
532
533           netstring => $string
534               Formats the given value as netstring
535               (http://cr.yp.to/proto/netstrings.txt, this is not a
536               recommendation to use them).
537
538           packstring => $format, $data
539               An octet string prefixed with an encoded length. The encoding
540               $format uses the same format as a Perl "pack" format, but must
541               specify a single integer only (only one of "cCsSlLqQiInNvVjJw"
542               is allowed, plus an optional "!", "<" or ">" modifier).
543
544           json => $array_or_hashref
545               Encodes the given hash or array reference into a JSON object.
546               Unless you provide your own JSON object, this means it will be
547               encoded to JSON text in UTF-8.
548
549               JSON objects (and arrays) are self-delimiting, so you can write
550               JSON at one end of a handle and read them at the other end
551               without using any additional framing.
552
553               The generated JSON text is guaranteed not to contain any
554               newlines: While this module doesn't need delimiters after or
555               between JSON texts to be able to read them, many other
556               languages depend on that.
557
558               A simple RPC protocol that interoperates easily with others is
559               to send JSON arrays (or objects, although arrays are usually
560               the better choice as they mimic how function argument passing
561               works) and a newline after each JSON text:
562
563                  $handle->push_write (json => ["method", "arg1", "arg2"]); # whatever
564                  $handle->push_write ("\012");
565
566               An AnyEvent::Handle receiver would simply use the "json" read
567               type and rely on the fact that the newline will be skipped as
568               leading whitespace:
569
570                  $handle->push_read (json => sub { my $array = $_[1]; ... });
571
572               Other languages could read single lines terminated by a newline
573               and pass this line into their JSON decoder of choice.
574
575           storable => $reference
576               Freezes the given reference using Storable and writes it to the
577               handle. Uses the "nfreeze" format.
578
579       $handle->push_shutdown
580           Sometimes you know you want to close the socket after writing your
581           data before it was actually written. One way to do that is to
582           replace your "on_drain" handler by a callback that shuts down the
583           socket (and set "low_water_mark" to 0). This method is a shorthand
584           for just that, and replaces the "on_drain" callback with:
585
586              sub { shutdown $_[0]{fh}, 1 }    # for push_shutdown
587
588           This simply shuts down the write side and signals an EOF condition
589           to the the peer.
590
591           You can rely on the normal read queue and "on_eof" handling
592           afterwards. This is the cleanest way to close a connection.
593
594           This method may invoke callbacks (and therefore the handle might be
595           destroyed after it returns).
596
597       custom write types - Package::anyevent_write_type $handle, @args
598           Instead of one of the predefined types, you can also specify the
599           name of a package. AnyEvent will try to load the package and then
600           expects to find a function named "anyevent_write_type" inside. If
601           it isn't found, it progressively tries to load the parent package
602           until it either finds the function (good) or runs out of packages
603           (bad).
604
605           Whenever the given "type" is used, "push_write" will the function
606           with the handle object and the remaining arguments.
607
608           The function is supposed to return a single octet string that will
609           be appended to the write buffer, so you cna mentally treat this
610           function as a "arguments to on-the-wire-format" converter.
611
612           Example: implement a custom write type "join" that joins the
613           remaining arguments using the first one.
614
615              $handle->push_write (My::Type => " ", 1,2,3);
616
617              # uses the following package, which can be defined in the "My::Type" or in
618              # the "My" modules to be auto-loaded, or just about anywhere when the
619              # My::Type::anyevent_write_type is defined before invoking it.
620
621              package My::Type;
622
623              sub anyevent_write_type {
624                 my ($handle, $delim, @args) = @_;
625
626                 join $delim, @args
627              }
628
629   READ QUEUE
630       AnyEvent::Handle manages two queues per handle, one for writing and one
631       for reading.
632
633       The read queue is more complex than the write queue. It can be used in
634       two ways, the "simple" way, using only "on_read" and the "complex" way,
635       using a queue.
636
637       In the simple case, you just install an "on_read" callback and whenever
638       new data arrives, it will be called. You can then remove some data (if
639       enough is there) from the read buffer ("$handle->rbuf"). Or you cna
640       leave the data there if you want to accumulate more (e.g. when only a
641       partial message has been received so far).
642
643       In the more complex case, you want to queue multiple callbacks. In this
644       case, AnyEvent::Handle will call the first queued callback each time
645       new data arrives (also the first time it is queued) and removes it when
646       it has done its job (see "push_read", below).
647
648       This way you can, for example, push three line-reads, followed by
649       reading a chunk of data, and AnyEvent::Handle will execute them in
650       order.
651
652       Example 1: EPP protocol parser. EPP sends 4 byte length info, followed
653       by the specified number of bytes which give an XML datagram.
654
655          # in the default state, expect some header bytes
656          $handle->on_read (sub {
657             # some data is here, now queue the length-header-read (4 octets)
658             shift->unshift_read (chunk => 4, sub {
659                # header arrived, decode
660                my $len = unpack "N", $_[1];
661
662                # now read the payload
663                shift->unshift_read (chunk => $len, sub {
664                   my $xml = $_[1];
665                   # handle xml
666                });
667             });
668          });
669
670       Example 2: Implement a client for a protocol that replies either with
671       "OK" and another line or "ERROR" for the first request that is sent,
672       and 64 bytes for the second request. Due to the availability of a
673       queue, we can just pipeline sending both requests and manipulate the
674       queue as necessary in the callbacks.
675
676       When the first callback is called and sees an "OK" response, it will
677       "unshift" another line-read. This line-read will be queued before the
678       64-byte chunk callback.
679
680          # request one, returns either "OK + extra line" or "ERROR"
681          $handle->push_write ("request 1\015\012");
682
683          # we expect "ERROR" or "OK" as response, so push a line read
684          $handle->push_read (line => sub {
685             # if we got an "OK", we have to _prepend_ another line,
686             # so it will be read before the second request reads its 64 bytes
687             # which are already in the queue when this callback is called
688             # we don't do this in case we got an error
689             if ($_[1] eq "OK") {
690                $_[0]->unshift_read (line => sub {
691                   my $response = $_[1];
692                   ...
693                });
694             }
695          });
696
697          # request two, simply returns 64 octets
698          $handle->push_write ("request 2\015\012");
699
700          # simply read 64 bytes, always
701          $handle->push_read (chunk => 64, sub {
702             my $response = $_[1];
703             ...
704          });
705
706       $handle->on_read ($cb)
707           This replaces the currently set "on_read" callback, or clears it
708           (when the new callback is "undef"). See the description of
709           "on_read" in the constructor.
710
711           This method may invoke callbacks (and therefore the handle might be
712           destroyed after it returns).
713
714       $handle->rbuf
715           Returns the read buffer (as a modifiable lvalue).
716
717           You can access the read buffer directly as the "->{rbuf}" member,
718           if you want. However, the only operation allowed on the read buffer
719           (apart from looking at it) is removing data from its beginning.
720           Otherwise modifying or appending to it is not allowed and will lead
721           to hard-to-track-down bugs.
722
723           NOTE: The read buffer should only be used or modified if the
724           "on_read", "push_read" or "unshift_read" methods are used. The
725           other read methods automatically manage the read buffer.
726
727       $handle->push_read ($cb)
728       $handle->unshift_read ($cb)
729           Append the given callback to the end of the queue ("push_read") or
730           prepend it ("unshift_read").
731
732           The callback is called each time some additional read data arrives.
733
734           It must check whether enough data is in the read buffer already.
735
736           If not enough data is available, it must return the empty list or a
737           false value, in which case it will be called repeatedly until
738           enough data is available (or an error condition is detected).
739
740           If enough data was available, then the callback must remove all
741           data it is interested in (which can be none at all) and return a
742           true value. After returning true, it will be removed from the
743           queue.
744
745           These methods may invoke callbacks (and therefore the handle might
746           be destroyed after it returns).
747
748       $handle->push_read (type => @args, $cb)
749       $handle->unshift_read (type => @args, $cb)
750           Instead of providing a callback that parses the data itself you can
751           chose between a number of predefined parsing formats, for chunks of
752           data, lines etc. You can also specify the (fully qualified) name of
753           a package, in which case AnyEvent tries to load the package and
754           then expects to find the "anyevent_read_type" function inside (see
755           "custom read types", below).
756
757           Predefined types are (if you have ideas for additional types, feel
758           free to drop by and tell us):
759
760           chunk => $octets, $cb->($handle, $data)
761               Invoke the callback only once $octets bytes have been read.
762               Pass the data read to the callback. The callback will never be
763               called with less data.
764
765               Example: read 2 bytes.
766
767                  $handle->push_read (chunk => 2, sub {
768                     warn "yay ", unpack "H*", $_[1];
769                  });
770
771           line => [$eol, ]$cb->($handle, $line, $eol)
772               The callback will be called only once a full line (including
773               the end of line marker, $eol) has been read. This line
774               (excluding the end of line marker) will be passed to the
775               callback as second argument ($line), and the end of line marker
776               as the third argument ($eol).
777
778               The end of line marker, $eol, can be either a string, in which
779               case it will be interpreted as a fixed record end marker, or it
780               can be a regex object (e.g. created by "qr"), in which case it
781               is interpreted as a regular expression.
782
783               The end of line marker argument $eol is optional, if it is
784               missing (NOT undef), then "qr|\015?\012|" is used (which is
785               good for most internet protocols).
786
787               Partial lines at the end of the stream will never be returned,
788               as they are not marked by the end of line marker.
789
790           regex => $accept[, $reject[, $skip], $cb->($handle, $data)
791               Makes a regex match against the regex object $accept and
792               returns everything up to and including the match.
793
794               Example: read a single line terminated by '\n'.
795
796                  $handle->push_read (regex => qr<\n>, sub { ... });
797
798               If $reject is given and not undef, then it determines when the
799               data is to be rejected: it is matched against the data when the
800               $accept regex does not match and generates an "EBADMSG" error
801               when it matches. This is useful to quickly reject wrong data
802               (to avoid waiting for a timeout or a receive buffer overflow).
803
804               Example: expect a single decimal number followed by whitespace,
805               reject anything else (not the use of an anchor).
806
807                  $handle->push_read (regex => qr<^[0-9]+\s>, qr<[^0-9]>, sub { ... });
808
809               If $skip is given and not "undef", then it will be matched
810               against the receive buffer when neither $accept nor $reject
811               match, and everything preceding and including the match will be
812               accepted unconditionally. This is useful to skip large amounts
813               of data that you know cannot be matched, so that the $accept or
814               $reject regex do not have to start matching from the beginning.
815               This is purely an optimisation and is usually worth only when
816               you expect more than a few kilobytes.
817
818               Example: expect a http header, which ends at
819               "\015\012\015\012". Since we expect the header to be very large
820               (it isn't in practise, but...), we use a skip regex to skip
821               initial portions. The skip regex is tricky in that it only
822               accepts something not ending in either \015 or \012, as these
823               are required for the accept regex.
824
825                  $handle->push_read (regex =>
826                     qr<\015\012\015\012>,
827                     undef, # no reject
828                     qr<^.*[^\015\012]>,
829                     sub { ... });
830
831           netstring => $cb->($handle, $string)
832               A netstring (http://cr.yp.to/proto/netstrings.txt, this is not
833               an endorsement).
834
835               Throws an error with $! set to EBADMSG on format violations.
836
837           packstring => $format, $cb->($handle, $string)
838               An octet string prefixed with an encoded length. The encoding
839               $format uses the same format as a Perl "pack" format, but must
840               specify a single integer only (only one of "cCsSlLqQiInNvVjJw"
841               is allowed, plus an optional "!", "<" or ">" modifier).
842
843               For example, DNS over TCP uses a prefix of "n" (2 octet network
844               order), EPP uses a prefix of "N" (4 octtes).
845
846               Example: read a block of data prefixed by its length in BER-
847               encoded format (very efficient).
848
849                  $handle->push_read (packstring => "w", sub {
850                     my ($handle, $data) = @_;
851                  });
852
853           json => $cb->($handle, $hash_or_arrayref)
854               Reads a JSON object or array, decodes it and passes it to the
855               callback. When a parse error occurs, an "EBADMSG" error will be
856               raised.
857
858               If a "json" object was passed to the constructor, then that
859               will be used for the final decode, otherwise it will create a
860               JSON coder expecting UTF-8.
861
862               This read type uses the incremental parser available with JSON
863               version 2.09 (and JSON::XS version 2.2) and above. You have to
864               provide a dependency on your own: this module will load the
865               JSON module, but AnyEvent does not depend on it itself.
866
867               Since JSON texts are fully self-delimiting, the "json" read and
868               write types are an ideal simple RPC protocol: just exchange
869               JSON datagrams. See the "json" write type description, above,
870               for an actual example.
871
872           storable => $cb->($handle, $ref)
873               Deserialises a Storable frozen representation as written by the
874               "storable" write type (BER-encoded length prefix followed by
875               nfreeze'd data).
876
877               Raises "EBADMSG" error if the data could not be decoded.
878
879       custom read types - Package::anyevent_read_type $handle, $cb, @args
880           Instead of one of the predefined types, you can also specify the
881           name of a package. AnyEvent will try to load the package and then
882           expects to find a function named "anyevent_read_type" inside. If it
883           isn't found, it progressively tries to load the parent package
884           until it either finds the function (good) or runs out of packages
885           (bad).
886
887           Whenever this type is used, "push_read" will invoke the function
888           with the handle object, the original callback and the remaining
889           arguments.
890
891           The function is supposed to return a callback (usually a closure)
892           that works as a plain read callback (see "->push_read ($cb)"), so
893           you can mentally treat the function as a "configurable read type to
894           read callback" converter.
895
896           It should invoke the original callback when it is done reading
897           (remember to pass $handle as first argument as all other callbacks
898           do that, although there is no strict requirement on this).
899
900           For examples, see the source of this module (perldoc -m
901           AnyEvent::Handle, search for "register_read_type")).
902
903       $handle->stop_read
904       $handle->start_read
905           In rare cases you actually do not want to read anything from the
906           socket. In this case you can call "stop_read". Neither "on_read"
907           nor any queued callbacks will be executed then. To start reading
908           again, call "start_read".
909
910           Note that AnyEvent::Handle will automatically "start_read" for you
911           when you change the "on_read" callback or push/unshift a read
912           callback, and it will automatically "stop_read" for you when
913           neither "on_read" is set nor there are any read requests in the
914           queue.
915
916           These methods will have no effect when in TLS mode (as TLS doesn't
917           support half-duplex connections).
918
919       $handle->starttls ($tls[, $tls_ctx])
920           Instead of starting TLS negotiation immediately when the
921           AnyEvent::Handle object is created, you can also do that at a later
922           time by calling "starttls".
923
924           Starting TLS is currently an asynchronous operation - when you push
925           some write data and then call "->starttls" then TLS negotiation
926           will start immediately, after which the queued write data is then
927           sent.
928
929           The first argument is the same as the "tls" constructor argument
930           (either "connect", "accept" or an existing Net::SSLeay object).
931
932           The second argument is the optional "AnyEvent::TLS" object that is
933           used when AnyEvent::Handle has to create its own TLS connection
934           object, or a hash reference with "key => value" pairs that will be
935           used to construct a new context.
936
937           The TLS connection object will end up in "$handle->{tls}", the TLS
938           context in "$handle->{tls_ctx}" after this call and can be used or
939           changed to your liking. Note that the handshake might have already
940           started when this function returns.
941
942           Due to bugs in OpenSSL, it might or might not be possible to do
943           multiple handshakes on the same stream. Best do not attempt to use
944           the stream after stopping TLS.
945
946           This method may invoke callbacks (and therefore the handle might be
947           destroyed after it returns).
948
949       $handle->stoptls
950           Shuts down the SSL connection - this makes a proper EOF handshake
951           by sending a close notify to the other side, but since OpenSSL
952           doesn't support non-blocking shut downs, it is not guaranteed that
953           you can re-use the stream afterwards.
954
955           This method may invoke callbacks (and therefore the handle might be
956           destroyed after it returns).
957
958       $handle->destroy
959           Shuts down the handle object as much as possible - this call
960           ensures that no further callbacks will be invoked and as many
961           resources as possible will be freed. Any method you will call on
962           the handle object after destroying it in this way will be silently
963           ignored (and it will return the empty list).
964
965           Normally, you can just "forget" any references to an
966           AnyEvent::Handle object and it will simply shut down. This works in
967           fatal error and EOF callbacks, as well as code outside. It does NOT
968           work in a read or write callback, so when you want to destroy the
969           AnyEvent::Handle object from within such an callback. You MUST call
970           "->destroy" explicitly in that case.
971
972           Destroying the handle object in this way has the advantage that
973           callbacks will be removed as well, so if those are the only
974           reference holders (as is common), then one doesn't need to do
975           anything special to break any reference cycles.
976
977           The handle might still linger in the background and write out
978           remaining data, as specified by the "linger" option, however.
979
980       $handle->destroyed
981           Returns false as long as the handle hasn't been destroyed by a call
982           to "->destroy", true otherwise.
983
984           Can be useful to decide whether the handle is still valid after
985           some callback possibly destroyed the handle. For example,
986           "->push_write", "->starttls" and other methods can call user
987           callbacks, which in turn can destroy the handle, so work can be
988           avoided by checking sometimes:
989
990              $hdl->starttls ("accept");
991              return if $hdl->destroyed;
992              $hdl->push_write (...
993
994           Note that the call to "push_write" will silently be ignored if the
995           handle has been destroyed, so often you can just ignore the
996           possibility of the handle being destroyed.
997
998       AnyEvent::Handle::TLS_CTX
999           This function creates and returns the AnyEvent::TLS object used by
1000           default for TLS mode.
1001
1002           The context is created by calling AnyEvent::TLS without any
1003           arguments.
1004

NONFREQUENTLY ASKED QUESTIONS

1006       I "undef" the AnyEvent::Handle reference inside my callback and still
1007       get further invocations!
1008           That's because AnyEvent::Handle keeps a reference to itself when
1009           handling read or write callbacks.
1010
1011           It is only safe to "forget" the reference inside EOF or error
1012           callbacks, from within all other callbacks, you need to explicitly
1013           call the "->destroy" method.
1014
1015       I get different callback invocations in TLS mode/Why can't I pause
1016       reading?
1017           Unlike, say, TCP, TLS connections do not consist of two independent
1018           communication channels, one for each direction. Or put differently.
1019           The read and write directions are not independent of each other:
1020           you cannot write data unless you are also prepared to read, and
1021           vice versa.
1022
1023           This can mean than, in TLS mode, you might get "on_error" or
1024           "on_eof" callback invocations when you are not expecting any read
1025           data - the reason is that AnyEvent::Handle always reads in TLS
1026           mode.
1027
1028           During the connection, you have to make sure that you always have a
1029           non-empty read-queue, or an "on_read" watcher. At the end of the
1030           connection (or when you no longer want to use it) you can call the
1031           "destroy" method.
1032
1033       How do I read data until the other side closes the connection?
1034           If you just want to read your data into a perl scalar, the easiest
1035           way to achieve this is by setting an "on_read" callback that does
1036           nothing, clearing the "on_eof" callback and in the "on_error"
1037           callback, the data will be in "$_[0]{rbuf}":
1038
1039              $handle->on_read (sub { });
1040              $handle->on_eof (undef);
1041              $handle->on_error (sub {
1042                 my $data = delete $_[0]{rbuf};
1043              });
1044
1045           The reason to use "on_error" is that TCP connections, due to
1046           latencies and packets loss, might get closed quite violently with
1047           an error, when in fact, all data has been received.
1048
1049           It is usually better to use acknowledgements when transferring
1050           data, to make sure the other side hasn't just died and you got the
1051           data intact. This is also one reason why so many internet protocols
1052           have an explicit QUIT command.
1053
1054       I don't want to destroy the handle too early - how do I wait until all
1055       data has been written?
1056           After writing your last bits of data, set the "on_drain" callback
1057           and destroy the handle in there - with the default setting of
1058           "low_water_mark" this will be called precisely when all data has
1059           been written to the socket:
1060
1061              $handle->push_write (...);
1062              $handle->on_drain (sub {
1063                 warn "all data submitted to the kernel\n";
1064                 undef $handle;
1065              });
1066
1067           If you just want to queue some data and then signal EOF to the
1068           other side, consider using "->push_shutdown" instead.
1069
1070       I want to contact a TLS/SSL server, I don't care about security.
1071           If your TLS server is a pure TLS server (e.g. HTTPS) that only
1072           speaks TLS, simply connect to it and then create the
1073           AnyEvent::Handle with the "tls" parameter:
1074
1075              tcp_connect $host, $port, sub {
1076                 my ($fh) = @_;
1077
1078                 my $handle = new AnyEvent::Handle
1079                    fh  => $fh,
1080                    tls => "connect",
1081                    on_error => sub { ... };
1082
1083                 $handle->push_write (...);
1084              };
1085
1086       I want to contact a TLS/SSL server, I do care about security.
1087           Then you should additionally enable certificate verification,
1088           including peername verification, if the protocol you use supports
1089           it (see AnyEvent::TLS, "verify_peername").
1090
1091           E.g. for HTTPS:
1092
1093              tcp_connect $host, $port, sub {
1094                 my ($fh) = @_;
1095
1096                  my $handle = new AnyEvent::Handle
1097                     fh       => $fh,
1098                     peername => $host,
1099                     tls      => "connect",
1100                     tls_ctx  => { verify => 1, verify_peername => "https" },
1101                     ...
1102
1103           Note that you must specify the hostname you connected to (or
1104           whatever "peername" the protocol needs) as the "peername" argument,
1105           otherwise no peername verification will be done.
1106
1107           The above will use the system-dependent default set of trusted CA
1108           certificates. If you want to check against a specific CA, add the
1109           "ca_file" (or "ca_cert") arguments to "tls_ctx":
1110
1111                  tls_ctx  => {
1112                     verify          => 1,
1113                     verify_peername => "https",
1114                     ca_file         => "my-ca-cert.pem",
1115                  },
1116
1117       I want to create a TLS/SSL server, how do I do that?
1118           Well, you first need to get a server certificate and key. You have
1119           three options: a) ask a CA (buy one, use cacert.org etc.) b) create
1120           a self-signed certificate (cheap. check the search engine of your
1121           choice, there are many tutorials on the net) or c) make your own CA
1122           (tinyca2 is a nice program for that purpose).
1123
1124           Then create a file with your private key (in PEM format, see
1125           AnyEvent::TLS), followed by the certificate (also in PEM format).
1126           The file should then look like this:
1127
1128              -----BEGIN RSA PRIVATE KEY-----
1129              ...header data
1130              ... lots of base64'y-stuff
1131              -----END RSA PRIVATE KEY-----
1132
1133              -----BEGIN CERTIFICATE-----
1134              ... lots of base64'y-stuff
1135              -----END CERTIFICATE-----
1136
1137           The important bits are the "PRIVATE KEY" and "CERTIFICATE" parts.
1138           Then specify this file as "cert_file":
1139
1140              tcp_server undef, $port, sub {
1141                 my ($fh) = @_;
1142
1143                 my $handle = new AnyEvent::Handle
1144                    fh       => $fh,
1145                    tls      => "accept",
1146                    tls_ctx  => { cert_file => "my-server-keycert.pem" },
1147                    ...
1148
1149           When you have intermediate CA certificates that your clients might
1150           not know about, just append them to the "cert_file".
1151

SUBCLASSING AnyEvent::Handle

1153       In many cases, you might want to subclass AnyEvent::Handle.
1154
1155       To make this easier, a given version of AnyEvent::Handle uses these
1156       conventions:
1157
1158       ·   all constructor arguments become object members.
1159
1160           At least initially, when you pass a "tls"-argument to the
1161           constructor it will end up in "$handle->{tls}". Those members might
1162           be changed or mutated later on (for example "tls" will hold the TLS
1163           connection object).
1164
1165       ·   other object member names are prefixed with an "_".
1166
1167           All object members not explicitly documented (internal use) are
1168           prefixed with an underscore character, so the remaining
1169           non-"_"-namespace is free for use for subclasses.
1170
1171       ·   all members not documented here and not prefixed with an underscore
1172           are free to use in subclasses.
1173
1174           Of course, new versions of AnyEvent::Handle may introduce more
1175           "public" member variables, but thats just life, at least it is
1176           documented.
1177

AUTHOR

1179       Robin Redeker "<elmex at ta-sa.org>", Marc Lehmann
1180       <schmorp@schmorp.de>.
1181
1182
1183
1184perl v5.12.1                      2010-06-08               AnyEvent::Handle(3)
Impressum