ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent/Handle.pm
(Generate patch)

Comparing AnyEvent/lib/AnyEvent/Handle.pm (file contents):
Revision 1.197 by root, Tue Aug 31 00:59:55 2010 UTC vs.
Revision 1.198 by root, Tue Aug 31 01:03:37 2010 UTC

30 30
31 $cv->recv; 31 $cv->recv;
32 32
33=head1 DESCRIPTION 33=head1 DESCRIPTION
34 34
35This module is a helper module to make it easier to do event-based I/O on 35This is a helper module to make it easier to do event-based I/O on
36stream-based filehandles (sockets, pipes or other stream things). 36stream-based filehandles (sockets, pipes, and other stream things).
37 37
38The L<AnyEvent::Intro> tutorial contains some well-documented 38The L<AnyEvent::Intro> tutorial contains some well-documented
39AnyEvent::Handle examples. 39AnyEvent::Handle examples.
40 40
41In the following, when the documentation refers to of "bytes" then this 41In the following, where the documentation refers to "bytes", it means
42means characters. As sysread and syswrite are used for all I/O, their 42characters. As sysread and syswrite are used for all I/O, their
43treatment of characters applies to this module as well. 43treatment of characters applies to this module as well.
44 44
45At the very minimum, you should specify C<fh> or C<connect>, and the 45At the very minimum, you should specify C<fh> or C<connect>, and the
46C<on_error> callback. 46C<on_error> callback.
47 47
118prepare the file handle with parameters required for the actual connect 118prepare the file handle with parameters required for the actual connect
119(as opposed to settings that can be changed when the connection is already 119(as opposed to settings that can be changed when the connection is already
120established). 120established).
121 121
122The return value of this callback should be the connect timeout value in 122The return value of this callback should be the connect timeout value in
123seconds (or C<0>, or C<undef>, or the empty list, to indicate the default 123seconds (or C<0>, or C<undef>, or the empty list, to indicate that the
124timeout is to be used). 124default timeout is to be used).
125 125
126=item on_connect => $cb->($handle, $host, $port, $retry->()) 126=item on_connect => $cb->($handle, $host, $port, $retry->())
127 127
128This callback is called when a connection has been successfully established. 128This callback is called when a connection has been successfully established.
129 129
130The actual numeric host and port (the socket peername) are passed as 130The peer's numeric host and port (the socket peername) are passed as
131parameters, together with a retry callback. 131parameters, together with a retry callback.
132 132
133When, for some reason, the handle is not acceptable, then calling 133If, for some reason, the handle is not acceptable, calling C<$retry>
134C<$retry> will continue with the next connection target (in case of 134will continue with the next connection target (in case of multi-homed
135multi-homed hosts or SRV records there can be multiple connection 135hosts or SRV records there can be multiple connection endpoints). At the
136endpoints). At the time it is called the read and write queues, eof 136time it is called the read and write queues, eof status, tls status and
137status, tls status and similar properties of the handle will have been 137similar properties of the handle will have been reset.
138reset.
139 138
140In most cases, ignoring the C<$retry> parameter is the way to go. 139In most cases, you should ignore the C<$retry> parameter.
141 140
142=item on_connect_error => $cb->($handle, $message) 141=item on_connect_error => $cb->($handle, $message)
143 142
144This callback is called when the connection could not be 143This callback is called when the connection could not be
145established. C<$!> will contain the relevant error code, and C<$message> a 144established. C<$!> will contain the relevant error code, and C<$message> a
152 151
153=item on_error => $cb->($handle, $fatal, $message) 152=item on_error => $cb->($handle, $fatal, $message)
154 153
155This is the error callback, which is called when, well, some error 154This is the error callback, which is called when, well, some error
156occured, such as not being able to resolve the hostname, failure to 155occured, such as not being able to resolve the hostname, failure to
157connect or a read error. 156connect, or a read error.
158 157
159Some errors are fatal (which is indicated by C<$fatal> being true). On 158Some errors are fatal (which is indicated by C<$fatal> being true). On
160fatal errors the handle object will be destroyed (by a call to C<< -> 159fatal errors the handle object will be destroyed (by a call to C<< ->
161destroy >>) after invoking the error callback (which means you are free to 160destroy >>) after invoking the error callback (which means you are free to
162examine the handle object). Examples of fatal errors are an EOF condition 161examine the handle object). Examples of fatal errors are an EOF condition
163with active (but unsatisifable) read watchers (C<EPIPE>) or I/O errors. In 162with active (but unsatisifable) read watchers (C<EPIPE>) or I/O errors. In
164cases where the other side can close the connection at their will it is 163cases where the other side can close the connection at will, it is
165often easiest to not report C<EPIPE> errors in this callback. 164often easiest to not report C<EPIPE> errors in this callback.
166 165
167AnyEvent::Handle tries to find an appropriate error code for you to check 166AnyEvent::Handle tries to find an appropriate error code for you to check
168against, but in some cases (TLS errors), this does not work well. It is 167against, but in some cases (TLS errors), this does not work well. It is
169recommended to always output the C<$message> argument in human-readable 168recommended to always output the C<$message> argument in human-readable
170error messages (it's usually the same as C<"$!">). 169error messages (it's usually the same as C<"$!">).
171 170
172Non-fatal errors can be retried by simply returning, but it is recommended 171Non-fatal errors can be retried by returning, but it is recommended
173to simply ignore this parameter and instead abondon the handle object 172to simply ignore this parameter and instead abondon the handle object
174when this callback is invoked. Examples of non-fatal errors are timeouts 173when this callback is invoked. Examples of non-fatal errors are timeouts
175C<ETIMEDOUT>) or badly-formatted data (C<EBADMSG>). 174C<ETIMEDOUT>) or badly-formatted data (C<EBADMSG>).
176 175
177On callback entrance, the value of C<$!> contains the operating system 176On entry to the callback, the value of C<$!> contains the operating
178error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or 177system error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or
179C<EPROTO>). 178C<EPROTO>).
180 179
181While not mandatory, it is I<highly> recommended to set this callback, as 180While not mandatory, it is I<highly> recommended to set this callback, as
182you will not be notified of errors otherwise. The default simply calls 181you will not be notified of errors otherwise. The default just calls
183C<croak>. 182C<croak>.
184 183
185=item on_read => $cb->($handle) 184=item on_read => $cb->($handle)
186 185
187This sets the default read callback, which is called when data arrives 186This sets the default read callback, which is called when data arrives
195the beginning from it. 194the beginning from it.
196 195
197You can also call C<< ->push_read (...) >> or any other function that 196You can also call C<< ->push_read (...) >> or any other function that
198modifies the read queue. Or do both. Or ... 197modifies the read queue. Or do both. Or ...
199 198
200When an EOF condition is detected then AnyEvent::Handle will first try to 199When an EOF condition is detected, AnyEvent::Handle will first try to
201feed all the remaining data to the queued callbacks and C<on_read> before 200feed all the remaining data to the queued callbacks and C<on_read> before
202calling the C<on_eof> callback. If no progress can be made, then a fatal 201calling the C<on_eof> callback. If no progress can be made, then a fatal
203error will be raised (with C<$!> set to C<EPIPE>). 202error will be raised (with C<$!> set to C<EPIPE>).
204 203
205Note that, unlike requests in the read queue, an C<on_read> callback 204Note that, unlike requests in the read queue, an C<on_read> callback
224set, then a fatal error will be raised with C<$!> set to <0>. 223set, then a fatal error will be raised with C<$!> set to <0>.
225 224
226=item on_drain => $cb->($handle) 225=item on_drain => $cb->($handle)
227 226
228This sets the callback that is called when the write buffer becomes empty 227This sets the callback that is called when the write buffer becomes empty
229(or when the callback is set and the buffer is empty already). 228(or immediately if the buffer is empty already).
230 229
231To append to the write buffer, use the C<< ->push_write >> method. 230To append to the write buffer, use the C<< ->push_write >> method.
232 231
233This callback is useful when you don't want to put all of your write data 232This callback is useful when you don't want to put all of your write data
234into the queue at once, for example, when you want to write the contents 233into the queue at once, for example, when you want to write the contents
246many seconds pass without a successful read or write on the underlying 245many seconds pass without a successful read or write on the underlying
247file handle (or a call to C<timeout_reset>), the C<on_timeout> callback 246file handle (or a call to C<timeout_reset>), the C<on_timeout> callback
248will be invoked (and if that one is missing, a non-fatal C<ETIMEDOUT> 247will be invoked (and if that one is missing, a non-fatal C<ETIMEDOUT>
249error will be raised). 248error will be raised).
250 249
251There are three variants of the timeouts that work fully independent 250There are three variants of the timeouts that work independently
252of each other, for both read and write, just read, and just write: 251of each other, for both read and write, just read, and just write:
253C<timeout>, C<rtimeout> and C<wtimeout>, with corresponding callbacks 252C<timeout>, C<rtimeout> and C<wtimeout>, with corresponding callbacks
254C<on_timeout>, C<on_rtimeout> and C<on_wtimeout>, and reset functions 253C<on_timeout>, C<on_rtimeout> and C<on_wtimeout>, and reset functions
255C<timeout_reset>, C<rtimeout_reset>, and C<wtimeout_reset>. 254C<timeout_reset>, C<rtimeout_reset>, and C<wtimeout_reset>.
256 255
257Note that timeout processing is also active when you currently do not have 256Note that timeout processing is active even when you do not have
258any outstanding read or write requests: If you plan to keep the connection 257any outstanding read or write requests: If you plan to keep the connection
259idle then you should disable the timout temporarily or ignore the timeout 258idle then you should disable the timeout temporarily or ignore the timeout
260in the C<on_timeout> callback, in which case AnyEvent::Handle will simply 259in the C<on_timeout> callback, in which case AnyEvent::Handle will simply
261restart the timeout. 260restart the timeout.
262 261
263Zero (the default) disables this timeout. 262Zero (the default) disables this timeout.
264 263
280amount of data without a callback ever being called as long as the line 279amount of data without a callback ever being called as long as the line
281isn't finished). 280isn't finished).
282 281
283=item autocork => <boolean> 282=item autocork => <boolean>
284 283
285When disabled (the default), then C<push_write> will try to immediately 284When disabled (the default), C<push_write> will try to immediately
286write the data to the handle, if possible. This avoids having to register 285write the data to the handle if possible. This avoids having to register
287a write watcher and wait for the next event loop iteration, but can 286a write watcher and wait for the next event loop iteration, but can
288be inefficient if you write multiple small chunks (on the wire, this 287be inefficient if you write multiple small chunks (on the wire, this
289disadvantage is usually avoided by your kernel's nagle algorithm, see 288disadvantage is usually avoided by your kernel's nagle algorithm, see
290C<no_delay>, but this option can save costly syscalls). 289C<no_delay>, but this option can save costly syscalls).
291 290
292When enabled, then writes will always be queued till the next event loop 291When enabled, writes will always be queued till the next event loop
293iteration. This is efficient when you do many small writes per iteration, 292iteration. This is efficient when you do many small writes per iteration,
294but less efficient when you do a single write only per iteration (or when 293but less efficient when you do a single write only per iteration (or when
295the write buffer often is full). It also increases write latency. 294the write buffer often is full). It also increases write latency.
296 295
297=item no_delay => <boolean> 296=item no_delay => <boolean>
301the Nagle algorithm, and usually it is beneficial. 300the Nagle algorithm, and usually it is beneficial.
302 301
303In some situations you want as low a delay as possible, which can be 302In some situations you want as low a delay as possible, which can be
304accomplishd by setting this option to a true value. 303accomplishd by setting this option to a true value.
305 304
306The default is your opertaing system's default behaviour (most likely 305The default is your operating system's default behaviour (most likely
307enabled), this option explicitly enables or disables it, if possible. 306enabled). This option explicitly enables or disables it, if possible.
308 307
309=item keepalive => <boolean> 308=item keepalive => <boolean>
310 309
311Enables (default disable) the SO_KEEPALIVE option on the stream socket: 310Enables (default disable) the SO_KEEPALIVE option on the stream socket:
312normally, TCP connections have no time-out once established, so TCP 311normally, TCP connections have no time-out once established, so TCP
313connections, once established, can stay alive forever even when the other 312connections, once established, can stay alive forever even when the other
314side has long gone. TCP keepalives are a cheap way to take down long-lived 313side has long gone. TCP keepalives are a cheap way to take down long-lived
315TCP connections whent he other side becomes unreachable. While the default 314TCP connections when the other side becomes unreachable. While the default
316is OS-dependent, TCP keepalives usually kick in after around two hours, 315is OS-dependent, TCP keepalives usually kick in after around two hours,
317and, if the other side doesn't reply, take down the TCP connection some 10 316and, if the other side doesn't reply, take down the TCP connection some 10
318to 15 minutes later. 317to 15 minutes later.
319 318
320It is harmless to specify this option for file handles that do not support 319It is harmless to specify this option for file handles that do not support
338already have occured on BSD systems), but at least it will protect you 337already have occured on BSD systems), but at least it will protect you
339from most attacks. 338from most attacks.
340 339
341=item read_size => <bytes> 340=item read_size => <bytes>
342 341
343The default read block size (the amount of bytes this module will 342The default read block size (the number of bytes this module will
344try to read during each loop iteration, which affects memory 343try to read during each loop iteration, which affects memory
345requirements). Default: C<8192>. 344requirements). Default: C<8192>.
346 345
347=item low_water_mark => <bytes> 346=item low_water_mark => <bytes>
348 347
349Sets the amount of bytes (default: C<0>) that make up an "empty" write 348Sets the number of bytes (default: C<0>) that make up an "empty" write
350buffer: If the write reaches this size or gets even samller it is 349buffer: If the buffer reaches this size or gets even samller it is
351considered empty. 350considered empty.
352 351
353Sometimes it can be beneficial (for performance reasons) to add data to 352Sometimes it can be beneficial (for performance reasons) to add data to
354the write buffer before it is fully drained, but this is a rare case, as 353the write buffer before it is fully drained, but this is a rare case, as
355the operating system kernel usually buffers data as well, so the default 354the operating system kernel usually buffers data as well, so the default
356is good in almost all cases. 355is good in almost all cases.
357 356
358=item linger => <seconds> 357=item linger => <seconds>
359 358
360If non-zero (default: C<3600>), then the destructor of the 359If this is non-zero (default: C<3600>), the destructor of the
361AnyEvent::Handle object will check whether there is still outstanding 360AnyEvent::Handle object will check whether there is still outstanding
362write data and will install a watcher that will write this data to the 361write data and will install a watcher that will write this data to the
363socket. No errors will be reported (this mostly matches how the operating 362socket. No errors will be reported (this mostly matches how the operating
364system treats outstanding data at socket close time). 363system treats outstanding data at socket close time).
365 364
372A string used to identify the remote site - usually the DNS hostname 371A string used to identify the remote site - usually the DNS hostname
373(I<not> IDN!) used to create the connection, rarely the IP address. 372(I<not> IDN!) used to create the connection, rarely the IP address.
374 373
375Apart from being useful in error messages, this string is also used in TLS 374Apart from being useful in error messages, this string is also used in TLS
376peername verification (see C<verify_peername> in L<AnyEvent::TLS>). This 375peername verification (see C<verify_peername> in L<AnyEvent::TLS>). This
377verification will be skipped when C<peername> is not specified or 376verification will be skipped when C<peername> is not specified or is
378C<undef>. 377C<undef>.
379 378
380=item tls => "accept" | "connect" | Net::SSLeay::SSL object 379=item tls => "accept" | "connect" | Net::SSLeay::SSL object
381 380
382When this parameter is given, it enables TLS (SSL) mode, that means 381When this parameter is given, it enables TLS (SSL) mode, that means
408B<IMPORTANT:> since Net::SSLeay "objects" are really only integers, 407B<IMPORTANT:> since Net::SSLeay "objects" are really only integers,
409passing in the wrong integer will lead to certain crash. This most often 408passing in the wrong integer will lead to certain crash. This most often
410happens when one uses a stylish C<< tls => 1 >> and is surprised about the 409happens when one uses a stylish C<< tls => 1 >> and is surprised about the
411segmentation fault. 410segmentation fault.
412 411
413See the C<< ->starttls >> method for when need to start TLS negotiation later. 412Use the C<< ->starttls >> method if you need to start TLS negotiation later.
414 413
415=item tls_ctx => $anyevent_tls 414=item tls_ctx => $anyevent_tls
416 415
417Use the given C<AnyEvent::TLS> object to create the new TLS connection 416Use the given C<AnyEvent::TLS> object to create the new TLS connection
418(unless a connection object was specified directly). If this parameter is 417(unless a connection object was specified directly). If this parameter is
433 432
434TLS handshake failures will not cause C<on_error> to be invoked when this 433TLS handshake failures will not cause C<on_error> to be invoked when this
435callback is in effect, instead, the error message will be passed to C<on_starttls>. 434callback is in effect, instead, the error message will be passed to C<on_starttls>.
436 435
437Without this callback, handshake failures lead to C<on_error> being 436Without this callback, handshake failures lead to C<on_error> being
438called, as normal. 437called as usual.
439 438
440Note that you cannot call C<starttls> right again in this callback. If you 439Note that you cannot just call C<starttls> again in this callback. If you
441need to do that, start an zero-second timer instead whose callback can 440need to do that, start an zero-second timer instead whose callback can
442then call C<< ->starttls >> again. 441then call C<< ->starttls >> again.
443 442
444=item on_stoptls => $cb->($handle) 443=item on_stoptls => $cb->($handle)
445 444
1117partial message has been received so far), or change the read queue with 1116partial message has been received so far), or change the read queue with
1118e.g. C<push_read>. 1117e.g. C<push_read>.
1119 1118
1120In the more complex case, you want to queue multiple callbacks. In this 1119In the more complex case, you want to queue multiple callbacks. In this
1121case, AnyEvent::Handle will call the first queued callback each time new 1120case, AnyEvent::Handle will call the first queued callback each time new
1122data arrives (also the first time it is queued) and removes it when it has 1121data arrives (also the first time it is queued) and remove it when it has
1123done its job (see C<push_read>, below). 1122done its job (see C<push_read>, below).
1124 1123
1125This way you can, for example, push three line-reads, followed by reading 1124This way you can, for example, push three line-reads, followed by reading
1126a chunk of data, and AnyEvent::Handle will execute them in order. 1125a chunk of data, and AnyEvent::Handle will execute them in order.
1127 1126
1461the receive buffer when neither C<$accept> nor C<$reject> match, 1460the receive buffer when neither C<$accept> nor C<$reject> match,
1462and everything preceding and including the match will be accepted 1461and everything preceding and including the match will be accepted
1463unconditionally. This is useful to skip large amounts of data that you 1462unconditionally. This is useful to skip large amounts of data that you
1464know cannot be matched, so that the C<$accept> or C<$reject> regex do not 1463know cannot be matched, so that the C<$accept> or C<$reject> regex do not
1465have to start matching from the beginning. This is purely an optimisation 1464have to start matching from the beginning. This is purely an optimisation
1466and is usually worth only when you expect more than a few kilobytes. 1465and is usually worth it only when you expect more than a few kilobytes.
1467 1466
1468Example: expect a http header, which ends at C<\015\012\015\012>. Since we 1467Example: expect a http header, which ends at C<\015\012\015\012>. Since we
1469expect the header to be very large (it isn't in practise, but...), we use 1468expect the header to be very large (it isn't in practice, but...), we use
1470a skip regex to skip initial portions. The skip regex is tricky in that 1469a skip regex to skip initial portions. The skip regex is tricky in that
1471it only accepts something not ending in either \015 or \012, as these are 1470it only accepts something not ending in either \015 or \012, as these are
1472required for the accept regex. 1471required for the accept regex.
1473 1472
1474 $handle->push_read (regex => 1473 $handle->push_read (regex =>
1874context in C<< $handle->{tls_ctx} >> after this call and can be used or 1873context in C<< $handle->{tls_ctx} >> after this call and can be used or
1875changed to your liking. Note that the handshake might have already started 1874changed to your liking. Note that the handshake might have already started
1876when this function returns. 1875when this function returns.
1877 1876
1878Due to bugs in OpenSSL, it might or might not be possible to do multiple 1877Due to bugs in OpenSSL, it might or might not be possible to do multiple
1879handshakes on the same stream. Best do not attempt to use the stream after 1878handshakes on the same stream. It is best to not attempt to use the
1880stopping TLS. 1879stream after stopping TLS.
1881 1880
1882This method may invoke callbacks (and therefore the handle might be 1881This method may invoke callbacks (and therefore the handle might be
1883destroyed after it returns). 1882destroyed after it returns).
1884 1883
1885=cut 1884=cut
2115 2114
2116=item I get different callback invocations in TLS mode/Why can't I pause 2115=item I get different callback invocations in TLS mode/Why can't I pause
2117reading? 2116reading?
2118 2117
2119Unlike, say, TCP, TLS connections do not consist of two independent 2118Unlike, say, TCP, TLS connections do not consist of two independent
2120communication channels, one for each direction. Or put differently. The 2119communication channels, one for each direction. Or put differently, the
2121read and write directions are not independent of each other: you cannot 2120read and write directions are not independent of each other: you cannot
2122write data unless you are also prepared to read, and vice versa. 2121write data unless you are also prepared to read, and vice versa.
2123 2122
2124This can mean than, in TLS mode, you might get C<on_error> or C<on_eof> 2123This means that, in TLS mode, you might get C<on_error> or C<on_eof>
2125callback invocations when you are not expecting any read data - the reason 2124callback invocations when you are not expecting any read data - the reason
2126is that AnyEvent::Handle always reads in TLS mode. 2125is that AnyEvent::Handle always reads in TLS mode.
2127 2126
2128During the connection, you have to make sure that you always have a 2127During the connection, you have to make sure that you always have a
2129non-empty read-queue, or an C<on_read> watcher. At the end of the 2128non-empty read-queue, or an C<on_read> watcher. At the end of the
2143 my $data = delete $_[0]{rbuf}; 2142 my $data = delete $_[0]{rbuf};
2144 }); 2143 });
2145 2144
2146The reason to use C<on_error> is that TCP connections, due to latencies 2145The reason to use C<on_error> is that TCP connections, due to latencies
2147and packets loss, might get closed quite violently with an error, when in 2146and packets loss, might get closed quite violently with an error, when in
2148fact, all data has been received. 2147fact all data has been received.
2149 2148
2150It is usually better to use acknowledgements when transferring data, 2149It is usually better to use acknowledgements when transferring data,
2151to make sure the other side hasn't just died and you got the data 2150to make sure the other side hasn't just died and you got the data
2152intact. This is also one reason why so many internet protocols have an 2151intact. This is also one reason why so many internet protocols have an
2153explicit QUIT command. 2152explicit QUIT command.
2170consider using C<< ->push_shutdown >> instead. 2169consider using C<< ->push_shutdown >> instead.
2171 2170
2172=item I want to contact a TLS/SSL server, I don't care about security. 2171=item I want to contact a TLS/SSL server, I don't care about security.
2173 2172
2174If your TLS server is a pure TLS server (e.g. HTTPS) that only speaks TLS, 2173If your TLS server is a pure TLS server (e.g. HTTPS) that only speaks TLS,
2175simply connect to it and then create the AnyEvent::Handle with the C<tls> 2174connect to it and then create the AnyEvent::Handle with the C<tls>
2176parameter: 2175parameter:
2177 2176
2178 tcp_connect $host, $port, sub { 2177 tcp_connect $host, $port, sub {
2179 my ($fh) = @_; 2178 my ($fh) = @_;
2180 2179
2280 2279
2281=item * all members not documented here and not prefixed with an underscore 2280=item * all members not documented here and not prefixed with an underscore
2282are free to use in subclasses. 2281are free to use in subclasses.
2283 2282
2284Of course, new versions of AnyEvent::Handle may introduce more "public" 2283Of course, new versions of AnyEvent::Handle may introduce more "public"
2285member variables, but thats just life, at least it is documented. 2284member variables, but that's just life. At least it is documented.
2286 2285
2287=back 2286=back
2288 2287
2289=head1 AUTHOR 2288=head1 AUTHOR
2290 2289

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines