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                AE::log error => $msg;
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             say "got line <$line>";
30             $cv->send;
31          });
32
33          $cv->recv;
34

DESCRIPTION

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

METHODS

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

NONFREQUENTLY ASKED QUESTIONS

1202       I "undef" the AnyEvent::Handle reference inside my callback and still
1203       get further invocations!
1204           That's because AnyEvent::Handle keeps a reference to itself when
1205           handling read or write callbacks.
1206
1207           It is only safe to "forget" the reference inside EOF or error
1208           callbacks, from within all other callbacks, you need to explicitly
1209           call the "->destroy" method.
1210
1211       Why is my "on_eof" callback never called?
1212           Probably because your "on_error" callback is being called instead:
1213           When you have outstanding requests in your read queue, then an EOF
1214           is considered an error as you clearly expected some data.
1215
1216           To avoid this, make sure you have an empty read queue whenever your
1217           handle is supposed to be "idle" (i.e. connection closes are O.K.).
1218           You can set an "on_read" handler that simply pushes the first read
1219           requests in the queue.
1220
1221           See also the next question, which explains this in a bit more
1222           detail.
1223
1224       How can I serve requests in a loop?
1225           Most protocols consist of some setup phase (authentication for
1226           example) followed by a request handling phase, where the server
1227           waits for requests and handles them, in a loop.
1228
1229           There are two important variants: The first (traditional, better)
1230           variant handles requests until the server gets some QUIT command,
1231           causing it to close the connection first (highly desirable for a
1232           busy TCP server). A client dropping the connection is an error,
1233           which means this variant can detect an unexpected detection close.
1234
1235           To handle this case, always make sure you have a non-empty read
1236           queue, by pushing the "read request start" handler on it:
1237
1238              # we assume a request starts with a single line
1239              my @start_request; @start_request = (line => sub {
1240                 my ($hdl, $line) = @_;
1241
1242                 ... handle request
1243
1244                 # push next request read, possibly from a nested callback
1245                 $hdl->push_read (@start_request);
1246              });
1247
1248              # auth done, now go into request handling loop
1249              # now push the first @start_request
1250              $hdl->push_read (@start_request);
1251
1252           By always having an outstanding "push_read", the handle always
1253           expects some data and raises the "EPIPE" error when the connction
1254           is dropped unexpectedly.
1255
1256           The second variant is a protocol where the client can drop the
1257           connection at any time. For TCP, this means that the server machine
1258           may run out of sockets easier, and in general, it means you cannot
1259           distinguish a protocl failure/client crash from a normal connection
1260           close. Nevertheless, these kinds of protocols are common (and
1261           sometimes even the best solution to the problem).
1262
1263           Having an outstanding read request at all times is possible if you
1264           ignore "EPIPE" errors, but this doesn't help with when the client
1265           drops the connection during a request, which would still be an
1266           error.
1267
1268           A better solution is to push the initial request read in an
1269           "on_read" callback. This avoids an error, as when the server
1270           doesn't expect data (i.e. is idly waiting for the next request, an
1271           EOF will not raise an error, but simply result in an "on_eof"
1272           callback. It is also a bit slower and simpler:
1273
1274              # auth done, now go into request handling loop
1275              $hdl->on_read (sub {
1276                 my ($hdl) = @_;
1277
1278                 # called each time we receive data but the read queue is empty
1279                 # simply start read the request
1280
1281                 $hdl->push_read (line => sub {
1282                    my ($hdl, $line) = @_;
1283
1284                    ... handle request
1285
1286                    # do nothing special when the request has been handled, just
1287                    # let the request queue go empty.
1288                 });
1289              });
1290
1291       I get different callback invocations in TLS mode/Why can't I pause
1292       reading?
1293           Unlike, say, TCP, TLS connections do not consist of two independent
1294           communication channels, one for each direction. Or put differently,
1295           the read and write directions are not independent of each other:
1296           you cannot write data unless you are also prepared to read, and
1297           vice versa.
1298
1299           This means that, in TLS mode, you might get "on_error" or "on_eof"
1300           callback invocations when you are not expecting any read data - the
1301           reason is that AnyEvent::Handle always reads in TLS mode.
1302
1303           During the connection, you have to make sure that you always have a
1304           non-empty read-queue, or an "on_read" watcher. At the end of the
1305           connection (or when you no longer want to use it) you can call the
1306           "destroy" method.
1307
1308       How do I read data until the other side closes the connection?
1309           If you just want to read your data into a perl scalar, the easiest
1310           way to achieve this is by setting an "on_read" callback that does
1311           nothing, clearing the "on_eof" callback and in the "on_error"
1312           callback, the data will be in "$_[0]{rbuf}":
1313
1314              $handle->on_read (sub { });
1315              $handle->on_eof (undef);
1316              $handle->on_error (sub {
1317                 my $data = delete $_[0]{rbuf};
1318              });
1319
1320           Note that this example removes the "rbuf" member from the handle
1321           object, which is not normally allowed by the API. It is expressly
1322           permitted in this case only, as the handle object needs to be
1323           destroyed afterwards.
1324
1325           The reason to use "on_error" is that TCP connections, due to
1326           latencies and packets loss, might get closed quite violently with
1327           an error, when in fact all data has been received.
1328
1329           It is usually better to use acknowledgements when transferring
1330           data, to make sure the other side hasn't just died and you got the
1331           data intact. This is also one reason why so many internet protocols
1332           have an explicit QUIT command.
1333
1334       I don't want to destroy the handle too early - how do I wait until all
1335       data has been written?
1336           After writing your last bits of data, set the "on_drain" callback
1337           and destroy the handle in there - with the default setting of
1338           "low_water_mark" this will be called precisely when all data has
1339           been written to the socket:
1340
1341              $handle->push_write (...);
1342              $handle->on_drain (sub {
1343                 AE::log debug => "All data submitted to the kernel.";
1344                 undef $handle;
1345              });
1346
1347           If you just want to queue some data and then signal EOF to the
1348           other side, consider using "->push_shutdown" instead.
1349
1350       I want to contact a TLS/SSL server, I don't care about security.
1351           If your TLS server is a pure TLS server (e.g. HTTPS) that only
1352           speaks TLS, connect to it and then create the AnyEvent::Handle with
1353           the "tls" parameter:
1354
1355              tcp_connect $host, $port, sub {
1356                 my ($fh) = @_;
1357
1358                 my $handle = new AnyEvent::Handle
1359                    fh  => $fh,
1360                    tls => "connect",
1361                    on_error => sub { ... };
1362
1363                 $handle->push_write (...);
1364              };
1365
1366       I want to contact a TLS/SSL server, I do care about security.
1367           Then you should additionally enable certificate verification,
1368           including peername verification, if the protocol you use supports
1369           it (see AnyEvent::TLS, "verify_peername").
1370
1371           E.g. for HTTPS:
1372
1373              tcp_connect $host, $port, sub {
1374                 my ($fh) = @_;
1375
1376                  my $handle = new AnyEvent::Handle
1377                     fh       => $fh,
1378                     peername => $host,
1379                     tls      => "connect",
1380                     tls_ctx  => { verify => 1, verify_peername => "https" },
1381                     ...
1382
1383           Note that you must specify the hostname you connected to (or
1384           whatever "peername" the protocol needs) as the "peername" argument,
1385           otherwise no peername verification will be done.
1386
1387           The above will use the system-dependent default set of trusted CA
1388           certificates. If you want to check against a specific CA, add the
1389           "ca_file" (or "ca_cert") arguments to "tls_ctx":
1390
1391                  tls_ctx  => {
1392                     verify          => 1,
1393                     verify_peername => "https",
1394                     ca_file         => "my-ca-cert.pem",
1395                  },
1396
1397       I want to create a TLS/SSL server, how do I do that?
1398           Well, you first need to get a server certificate and key. You have
1399           three options: a) ask a CA (buy one, use cacert.org etc.) b) create
1400           a self-signed certificate (cheap. check the search engine of your
1401           choice, there are many tutorials on the net) or c) make your own CA
1402           (tinyca2 is a nice program for that purpose).
1403
1404           Then create a file with your private key (in PEM format, see
1405           AnyEvent::TLS), followed by the certificate (also in PEM format).
1406           The file should then look like this:
1407
1408              -----BEGIN RSA PRIVATE KEY-----
1409              ...header data
1410              ... lots of base64'y-stuff
1411              -----END RSA PRIVATE KEY-----
1412
1413              -----BEGIN CERTIFICATE-----
1414              ... lots of base64'y-stuff
1415              -----END CERTIFICATE-----
1416
1417           The important bits are the "PRIVATE KEY" and "CERTIFICATE" parts.
1418           Then specify this file as "cert_file":
1419
1420              tcp_server undef, $port, sub {
1421                 my ($fh) = @_;
1422
1423                 my $handle = new AnyEvent::Handle
1424                    fh       => $fh,
1425                    tls      => "accept",
1426                    tls_ctx  => { cert_file => "my-server-keycert.pem" },
1427                    ...
1428
1429           When you have intermediate CA certificates that your clients might
1430           not know about, just append them to the "cert_file".
1431

SUBCLASSING AnyEvent::Handle

1433       In many cases, you might want to subclass AnyEvent::Handle.
1434
1435       To make this easier, a given version of AnyEvent::Handle uses these
1436       conventions:
1437
1438       •   all constructor arguments become object members.
1439
1440           At least initially, when you pass a "tls"-argument to the
1441           constructor it will end up in "$handle->{tls}". Those members might
1442           be changed or mutated later on (for example "tls" will hold the TLS
1443           connection object).
1444
1445       •   other object member names are prefixed with an "_".
1446
1447           All object members not explicitly documented (internal use) are
1448           prefixed with an underscore character, so the remaining
1449           non-"_"-namespace is free for use for subclasses.
1450
1451       •   all members not documented here and not prefixed with an underscore
1452           are free to use in subclasses.
1453
1454           Of course, new versions of AnyEvent::Handle may introduce more
1455           "public" member variables, but that's just life. At least it is
1456           documented.
1457

AUTHOR

1459       Robin Redeker "<elmex at ta-sa.org>", Marc Lehmann
1460       <schmorp@schmorp.de>.
1461
1462
1463
1464perl v5.36.0                      2022-07-22               AnyEvent::Handle(3)
Impressum