35
This module is a helper module to make it easier to do event-based I/O on
36
stream-based filehandles (sockets, pipes or other stream things).
35
This is a helper module to make it easier to do event-based I/O on
36
stream-based filehandles (sockets, pipes, and other stream things).
38
38
The L<AnyEvent::Intro> tutorial contains some well-documented
39
39
AnyEvent::Handle examples.
41
In the following, when the documentation refers to of "bytes" then this
42
means characters. As sysread and syswrite are used for all I/O, their
41
In the following, where the documentation refers to "bytes", it means
42
characters. As sysread and syswrite are used for all I/O, their
43
43
treatment of characters applies to this module as well.
45
45
At the very minimum, you should specify C<fh> or C<connect>, and the
122
122
The return value of this callback should be the connect timeout value in
123
seconds (or C<0>, or C<undef>, or the empty list, to indicate the default
124
timeout is to be used).
123
seconds (or C<0>, or C<undef>, or the empty list, to indicate that the
124
default timeout is to be used).
126
126
=item on_connect => $cb->($handle, $host, $port, $retry->())
128
128
This callback is called when a connection has been successfully established.
130
The actual numeric host and port (the socket peername) are passed as
130
The peer's numeric host and port (the socket peername) are passed as
131
131
parameters, together with a retry callback.
133
When, for some reason, the handle is not acceptable, then calling
134
C<$retry> will continue with the next connection target (in case of
135
multi-homed hosts or SRV records there can be multiple connection
136
endpoints). At the time it is called the read and write queues, eof
137
status, tls status and similar properties of the handle will have been
133
If, for some reason, the handle is not acceptable, calling C<$retry>
134
will continue with the next connection target (in case of multi-homed
135
hosts or SRV records there can be multiple connection endpoints). At the
136
time it is called the read and write queues, eof status, tls status and
137
similar properties of the handle will have been reset.
140
In most cases, ignoring the C<$retry> parameter is the way to go.
139
In most cases, you should ignore the C<$retry> parameter.
142
141
=item on_connect_error => $cb->($handle, $message)
155
154
This is the error callback, which is called when, well, some error
156
155
occured, such as not being able to resolve the hostname, failure to
157
connect or a read error.
156
connect, or a read error.
159
158
Some errors are fatal (which is indicated by C<$fatal> being true). On
160
159
fatal errors the handle object will be destroyed (by a call to C<< ->
161
160
destroy >>) after invoking the error callback (which means you are free to
162
161
examine the handle object). Examples of fatal errors are an EOF condition
163
162
with active (but unsatisifable) read watchers (C<EPIPE>) or I/O errors. In
164
cases where the other side can close the connection at their will it is
163
cases where the other side can close the connection at will, it is
165
164
often easiest to not report C<EPIPE> errors in this callback.
167
166
AnyEvent::Handle tries to find an appropriate error code for you to check
169
168
recommended to always output the C<$message> argument in human-readable
170
169
error messages (it's usually the same as C<"$!">).
172
Non-fatal errors can be retried by simply returning, but it is recommended
171
Non-fatal errors can be retried by returning, but it is recommended
173
172
to simply ignore this parameter and instead abondon the handle object
174
173
when this callback is invoked. Examples of non-fatal errors are timeouts
175
174
C<ETIMEDOUT>) or badly-formatted data (C<EBADMSG>).
177
On callback entrance, the value of C<$!> contains the operating system
178
error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or
176
On entry to the callback, the value of C<$!> contains the operating
177
system error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or
181
180
While not mandatory, it is I<highly> recommended to set this callback, as
182
you will not be notified of errors otherwise. The default simply calls
181
you will not be notified of errors otherwise. The default just calls
185
184
=item on_read => $cb->($handle)
194
193
must not enlarge or modify the read buffer, you can only remove data at
195
194
the beginning from it.
197
When an EOF condition is detected then AnyEvent::Handle will first try to
196
You can also call C<< ->push_read (...) >> or any other function that
197
modifies the read queue. Or do both. Or ...
199
When an EOF condition is detected, AnyEvent::Handle will first try to
198
200
feed all the remaining data to the queued callbacks and C<on_read> before
199
201
calling the C<on_eof> callback. If no progress can be made, then a fatal
200
202
error will be raised (with C<$!> set to C<EPIPE>).
223
225
=item on_drain => $cb->($handle)
225
227
This sets the callback that is called when the write buffer becomes empty
226
(or when the callback is set and the buffer is empty already).
228
(or immediately if the buffer is empty already).
228
230
To append to the write buffer, use the C<< ->push_write >> method.
245
247
will be invoked (and if that one is missing, a non-fatal C<ETIMEDOUT>
246
248
error will be raised).
248
There are three variants of the timeouts that work fully independent
250
There are three variants of the timeouts that work independently
249
251
of each other, for both read and write, just read, and just write:
250
252
C<timeout>, C<rtimeout> and C<wtimeout>, with corresponding callbacks
251
253
C<on_timeout>, C<on_rtimeout> and C<on_wtimeout>, and reset functions
252
254
C<timeout_reset>, C<rtimeout_reset>, and C<wtimeout_reset>.
254
Note that timeout processing is also active when you currently do not have
256
Note that timeout processing is active even when you do not have
255
257
any outstanding read or write requests: If you plan to keep the connection
256
idle then you should disable the timout temporarily or ignore the timeout
258
idle then you should disable the timeout temporarily or ignore the timeout
257
259
in the C<on_timeout> callback, in which case AnyEvent::Handle will simply
258
260
restart the timeout.
280
282
=item autocork => <boolean>
282
When disabled (the default), then C<push_write> will try to immediately
283
write the data to the handle, if possible. This avoids having to register
284
When disabled (the default), C<push_write> will try to immediately
285
write the data to the handle if possible. This avoids having to register
284
286
a write watcher and wait for the next event loop iteration, but can
285
287
be inefficient if you write multiple small chunks (on the wire, this
286
288
disadvantage is usually avoided by your kernel's nagle algorithm, see
287
289
C<no_delay>, but this option can save costly syscalls).
289
When enabled, then writes will always be queued till the next event loop
291
When enabled, writes will always be queued till the next event loop
290
292
iteration. This is efficient when you do many small writes per iteration,
291
293
but less efficient when you do a single write only per iteration (or when
292
294
the write buffer often is full). It also increases write latency.
300
302
In some situations you want as low a delay as possible, which can be
301
303
accomplishd by setting this option to a true value.
303
The default is your opertaing system's default behaviour (most likely
304
enabled), this option explicitly enables or disables it, if possible.
305
The default is your operating system's default behaviour (most likely
306
enabled). This option explicitly enables or disables it, if possible.
306
308
=item keepalive => <boolean>
309
311
normally, TCP connections have no time-out once established, so TCP
310
312
connections, once established, can stay alive forever even when the other
311
313
side has long gone. TCP keepalives are a cheap way to take down long-lived
312
TCP connections whent he other side becomes unreachable. While the default
314
TCP connections when the other side becomes unreachable. While the default
313
315
is OS-dependent, TCP keepalives usually kick in after around two hours,
314
316
and, if the other side doesn't reply, take down the TCP connection some 10
315
317
to 15 minutes later.
338
340
=item read_size => <bytes>
340
The default read block size (the amount of bytes this module will
342
The default read block size (the number of bytes this module will
341
343
try to read during each loop iteration, which affects memory
342
344
requirements). Default: C<8192>.
344
346
=item low_water_mark => <bytes>
346
Sets the amount of bytes (default: C<0>) that make up an "empty" write
347
buffer: If the write reaches this size or gets even samller it is
348
Sets the number of bytes (default: C<0>) that make up an "empty" write
349
buffer: If the buffer reaches this size or gets even samller it is
348
350
considered empty.
350
352
Sometimes it can be beneficial (for performance reasons) to add data to
355
357
=item linger => <seconds>
357
If non-zero (default: C<3600>), then the destructor of the
359
If this is non-zero (default: C<3600>), the destructor of the
358
360
AnyEvent::Handle object will check whether there is still outstanding
359
361
write data and will install a watcher that will write this data to the
360
362
socket. No errors will be reported (this mostly matches how the operating
372
374
Apart from being useful in error messages, this string is also used in TLS
373
375
peername verification (see C<verify_peername> in L<AnyEvent::TLS>). This
374
verification will be skipped when C<peername> is not specified or
376
verification will be skipped when C<peername> is not specified or is
377
379
=item tls => "accept" | "connect" | Net::SSLeay::SSL object
407
409
happens when one uses a stylish C<< tls => 1 >> and is surprised about the
408
410
segmentation fault.
410
See the C<< ->starttls >> method for when need to start TLS negotiation later.
412
Use the C<< ->starttls >> method if you need to start TLS negotiation later.
412
414
=item tls_ctx => $anyevent_tls
432
434
callback is in effect, instead, the error message will be passed to C<on_starttls>.
434
436
Without this callback, handshake failures lead to C<on_error> being
437
Note that you cannot call C<starttls> right again in this callback. If you
439
Note that you cannot just call C<starttls> again in this callback. If you
438
440
need to do that, start an zero-second timer instead whose callback can
439
441
then call C<< ->starttls >> again.
558
560
$self->starttls (delete $self->{tls}, delete $self->{tls_ctx})
561
$self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
563
$self->on_drain (delete $self->{on_drain} ) if $self->{on_drain};
563
565
$self->start_read
564
566
if $self->{on_read} || @{ $self->{_queue} };
645
647
$_[0]{no_delay} = $_[1];
649
setsockopt $_[0]{fh}, Socket::IPPROTO_TCP (), Socket::TCP_NODELAY (), int $_[1]
649
setsockopt $_[0]{fh}, Socket::IPPROTO_TCP (), Socket::TCP_NODELAY (), int $_[1]
654
653
=item $handle->keepalive ($boolean)
768
767
*$timeout = sub {
769
768
my ($self, $new_value) = @_;
771
or Carp::croak "AnyEvent::Handle->$timeout called with negative timeout ($new_value), caught";
771
773
$self->{$timeout} = $new_value;
772
774
delete $self->{$tw}; &$cb;
935
937
do the job by specifying a type and type-specific arguments. You
936
938
can also specify the (fully qualified) name of a package, in which
937
939
case AnyEvent tries to load the package and then expects to find the
938
C<anyevent_read_type> function inside (see "custom write types", below).
940
C<anyevent_write_type> function inside (see "custom write types", below).
940
942
Predefined types are (if you have ideas for additional types, feel free to
941
943
drop by and tell us):
1110
1112
In the simple case, you just install an C<on_read> callback and whenever
1111
1113
new data arrives, it will be called. You can then remove some data (if
1112
enough is there) from the read buffer (C<< $handle->rbuf >>). Or you cna
1114
enough is there) from the read buffer (C<< $handle->rbuf >>). Or you can
1113
1115
leave the data there if you want to accumulate more (e.g. when only a
1114
partial message has been received so far).
1116
partial message has been received so far), or change the read queue with
1116
1119
In the more complex case, you want to queue multiple callbacks. In this
1117
1120
case, AnyEvent::Handle will call the first queued callback each time new
1118
data arrives (also the first time it is queued) and removes it when it has
1121
data arrives (also the first time it is queued) and remove it when it has
1119
1122
done its job (see C<push_read>, below).
1121
1124
This way you can, for example, push three line-reads, followed by reading
1271
1274
=item $handle->rbuf
1273
Returns the read buffer (as a modifiable lvalue).
1275
You can access the read buffer directly as the C<< ->{rbuf} >>
1276
member, if you want. However, the only operation allowed on the
1277
read buffer (apart from looking at it) is removing data from its
1278
beginning. Otherwise modifying or appending to it is not allowed and will
1279
lead to hard-to-track-down bugs.
1281
NOTE: The read buffer should only be used or modified if the C<on_read>,
1282
C<push_read> or C<unshift_read> methods are used. The other read methods
1283
automatically manage the read buffer.
1276
Returns the read buffer (as a modifiable lvalue). You can also access the
1277
read buffer directly as the C<< ->{rbuf} >> member, if you want (this is
1278
much faster, and no less clean).
1280
The only operation allowed on the read buffer (apart from looking at it)
1281
is removing data from its beginning. Otherwise modifying or appending to
1282
it is not allowed and will lead to hard-to-track-down bugs.
1284
NOTE: The read buffer should only be used or modified in the C<on_read>
1285
callback or when C<push_read> or C<unshift_read> are used with a single
1286
callback (i.e. untyped). Typed C<push_read> and C<unshift_read> methods
1287
will manage the read buffer on their own.
1459
1464
unconditionally. This is useful to skip large amounts of data that you
1460
1465
know cannot be matched, so that the C<$accept> or C<$reject> regex do not
1461
1466
have to start matching from the beginning. This is purely an optimisation
1462
and is usually worth only when you expect more than a few kilobytes.
1467
and is usually worth it only when you expect more than a few kilobytes.
1464
1469
Example: expect a http header, which ends at C<\015\012\015\012>. Since we
1465
expect the header to be very large (it isn't in practise, but...), we use
1470
expect the header to be very large (it isn't in practice, but...), we use
1466
1471
a skip regex to skip initial portions. The skip regex is tricky in that
1467
1472
it only accepts something not ending in either \015 or \012, as these are
1468
1473
required for the accept regex.
1872
1877
when this function returns.
1874
1879
Due to bugs in OpenSSL, it might or might not be possible to do multiple
1875
handshakes on the same stream. Best do not attempt to use the stream after
1880
handshakes on the same stream. It is best to not attempt to use the
1881
stream after stopping TLS.
1878
1883
This method may invoke callbacks (and therefore the handle might be
1879
1884
destroyed after it returns).
2115
2120
Unlike, say, TCP, TLS connections do not consist of two independent
2116
communication channels, one for each direction. Or put differently. The
2121
communication channels, one for each direction. Or put differently, the
2117
2122
read and write directions are not independent of each other: you cannot
2118
2123
write data unless you are also prepared to read, and vice versa.
2120
This can mean than, in TLS mode, you might get C<on_error> or C<on_eof>
2125
This means that, in TLS mode, you might get C<on_error> or C<on_eof>
2121
2126
callback invocations when you are not expecting any read data - the reason
2122
2127
is that AnyEvent::Handle always reads in TLS mode.
2142
2147
The reason to use C<on_error> is that TCP connections, due to latencies
2143
2148
and packets loss, might get closed quite violently with an error, when in
2144
fact, all data has been received.
2149
fact all data has been received.
2146
2151
It is usually better to use acknowledgements when transferring data,
2147
2152
to make sure the other side hasn't just died and you got the data
2168
2173
=item I want to contact a TLS/SSL server, I don't care about security.
2170
2175
If your TLS server is a pure TLS server (e.g. HTTPS) that only speaks TLS,
2171
simply connect to it and then create the AnyEvent::Handle with the C<tls>
2176
connect to it and then create the AnyEvent::Handle with the C<tls>
2174
2179
tcp_connect $host, $port, sub {
2278
2283
are free to use in subclasses.
2280
2285
Of course, new versions of AnyEvent::Handle may introduce more "public"
2281
member variables, but thats just life, at least it is documented.
2286
member variables, but that's just life. At least it is documented.