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.39 by root, Tue May 27 04:59:51 2008 UTC vs.
Revision 1.43 by root, Wed May 28 23:57:38 2008 UTC

2 2
3no warnings; 3no warnings;
4use strict; 4use strict;
5 5
6use AnyEvent (); 6use AnyEvent ();
7use AnyEvent::Util qw(WSAWOULDBLOCK); 7use AnyEvent::Util qw(WSAEWOULDBLOCK);
8use Scalar::Util (); 8use Scalar::Util ();
9use Carp (); 9use Carp ();
10use Fcntl (); 10use Fcntl ();
11use Errno qw/EAGAIN EINTR/; 11use Errno qw(EAGAIN EINTR);
12use Time::HiRes qw(time);
12 13
13=head1 NAME 14=head1 NAME
14 15
15AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent 16AnyEvent::Handle - non-blocking I/O on file handles via AnyEvent
16 17
73The filehandle this L<AnyEvent::Handle> object will operate on. 74The filehandle this L<AnyEvent::Handle> object will operate on.
74 75
75NOTE: The filehandle will be set to non-blocking (using 76NOTE: The filehandle will be set to non-blocking (using
76AnyEvent::Util::fh_nonblocking). 77AnyEvent::Util::fh_nonblocking).
77 78
78=item on_eof => $cb->($self) 79=item on_eof => $cb->($handle)
79 80
80Set the callback to be called on EOF. 81Set the callback to be called on EOF.
81 82
82While not mandatory, it is highly recommended to set an eof callback, 83While not mandatory, it is highly recommended to set an eof callback,
83otherwise you might end up with a closed socket while you are still 84otherwise you might end up with a closed socket while you are still
84waiting for data. 85waiting for data.
85 86
86=item on_error => $cb->($self) 87=item on_error => $cb->($handle)
87 88
88This is the fatal error callback, that is called when, well, a fatal error 89This is the fatal error callback, that is called when, well, a fatal error
89occurs, such as not being able to resolve the hostname, failure to connect 90occurs, such as not being able to resolve the hostname, failure to connect
90or a read error. 91or a read error.
91 92
92The object will not be in a usable state when this callback has been 93The object will not be in a usable state when this callback has been
93called. 94called.
94 95
95On callback entrance, the value of C<$!> contains the operating system 96On callback entrance, the value of C<$!> contains the operating system
96error (or C<ENOSPC>, C<EPIPE> or C<EBADMSG>). 97error (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT> or C<EBADMSG>).
97 98
98The callback should throw an exception. If it returns, then 99The callback should throw an exception. If it returns, then
99AnyEvent::Handle will C<croak> for you. 100AnyEvent::Handle will C<croak> for you.
100 101
101While not mandatory, it is I<highly> recommended to set this callback, as 102While not mandatory, it is I<highly> recommended to set this callback, as
102you will not be notified of errors otherwise. The default simply calls 103you will not be notified of errors otherwise. The default simply calls
103die. 104die.
104 105
105=item on_read => $cb->($self) 106=item on_read => $cb->($handle)
106 107
107This sets the default read callback, which is called when data arrives 108This sets the default read callback, which is called when data arrives
108and no read request is in the queue. 109and no read request is in the queue.
109 110
110To access (and remove data from) the read buffer, use the C<< ->rbuf >> 111To access (and remove data from) the read buffer, use the C<< ->rbuf >>
111method or access the C<$self->{rbuf}> member directly. 112method or access the C<$handle->{rbuf}> member directly.
112 113
113When an EOF condition is detected then AnyEvent::Handle will first try to 114When an EOF condition is detected then AnyEvent::Handle will first try to
114feed all the remaining data to the queued callbacks and C<on_read> before 115feed all the remaining data to the queued callbacks and C<on_read> before
115calling the C<on_eof> callback. If no progress can be made, then a fatal 116calling the C<on_eof> callback. If no progress can be made, then a fatal
116error will be raised (with C<$!> set to C<EPIPE>). 117error will be raised (with C<$!> set to C<EPIPE>).
117 118
118=item on_drain => $cb->() 119=item on_drain => $cb->($handle)
119 120
120This sets the callback that is called when the write buffer becomes empty 121This sets the callback that is called when the write buffer becomes empty
121(or when the callback is set and the buffer is empty already). 122(or when the callback is set and the buffer is empty already).
122 123
123To append to the write buffer, use the C<< ->push_write >> method. 124To append to the write buffer, use the C<< ->push_write >> method.
125
126=item timeout => $fractional_seconds
127
128If non-zero, then this enables an "inactivity" timeout: whenever this many
129seconds pass without a successful read or write on the underlying file
130handle, the C<on_timeout> callback will be invoked (and if that one is
131missing, an C<ETIMEDOUT> errror will be raised).
132
133Note that timeout processing is also active when you currently do not have
134any outstanding read or write requests: If you plan to keep the connection
135idle then you should disable the timout temporarily or ignore the timeout
136in the C<on_timeout> callback.
137
138Zero (the default) disables this timeout.
139
140=item on_timeout => $cb->($handle)
141
142Called whenever the inactivity timeout passes. If you return from this
143callback, then the timeout will be reset as if some activity had happened,
144so this condition is not fatal in any way.
124 145
125=item rbuf_max => <bytes> 146=item rbuf_max => <bytes>
126 147
127If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>) 148If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>)
128when the read buffer ever (strictly) exceeds this size. This is useful to 149when the read buffer ever (strictly) exceeds this size. This is useful to
168 189
169Use the given Net::SSLeay::CTX object to create the new TLS connection 190Use the given Net::SSLeay::CTX object to create the new TLS connection
170(unless a connection object was specified directly). If this parameter is 191(unless a connection object was specified directly). If this parameter is
171missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>. 192missing, then AnyEvent::Handle will use C<AnyEvent::Handle::TLS_CTX>.
172 193
194=item json => JSON or JSON::XS object
195
196This is the json coder object used by the C<json> read and write types.
197
198If you don't supply it, then AnyEvent::Handle will create and use a
199suitable one, which will write and expect UTF-8 encoded JSON texts.
200
201Note that you are responsible to depend on the JSON module if you want to
202use this functionality, as AnyEvent does not have a dependency itself.
203
173=item filter_r => $cb 204=item filter_r => $cb
174 205
175=item filter_w => $cb 206=item filter_w => $cb
176 207
177These exist, but are undocumented at this time. 208These exist, but are undocumented at this time.
192 if ($self->{tls}) { 223 if ($self->{tls}) {
193 require Net::SSLeay; 224 require Net::SSLeay;
194 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx}); 225 $self->starttls (delete $self->{tls}, delete $self->{tls_ctx});
195 } 226 }
196 227
197 $self->on_eof (delete $self->{on_eof} ) if $self->{on_eof}; 228# $self->on_eof (delete $self->{on_eof} ) if $self->{on_eof}; # nop
198 $self->on_error (delete $self->{on_error}) if $self->{on_error}; 229# $self->on_error (delete $self->{on_error}) if $self->{on_error}; # nop
230# $self->on_read (delete $self->{on_read} ) if $self->{on_read}; # nop
199 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain}; 231 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
200 $self->on_read (delete $self->{on_read} ) if $self->{on_read}; 232
233 $self->{_activity} = time;
234 $self->_timeout;
201 235
202 $self->start_read; 236 $self->start_read;
203 237
204 $self 238 $self
205} 239}
252 286
253sub on_eof { 287sub on_eof {
254 $_[0]{on_eof} = $_[1]; 288 $_[0]{on_eof} = $_[1];
255} 289}
256 290
291=item $handle->on_timeout ($cb)
292
293Replace the current C<on_timeout> callback, or disables the callback
294(but not the timeout) if C<$cb> = C<undef>. See C<timeout> constructor
295argument.
296
297=cut
298
299sub on_timeout {
300 $_[0]{on_timeout} = $_[1];
301}
302
303#############################################################################
304
305=item $handle->timeout ($seconds)
306
307Configures (or disables) the inactivity timeout.
308
309=cut
310
311sub timeout {
312 my ($self, $timeout) = @_;
313
314 $self->{timeout} = $timeout;
315 $self->_timeout;
316}
317
318# reset the timeout watcher, as neccessary
319# also check for time-outs
320sub _timeout {
321 my ($self) = @_;
322
323 if ($self->{timeout}) {
324 my $NOW = time;
325
326 # when would the timeout trigger?
327 my $after = $self->{_activity} + $self->{timeout} - $NOW;
328
329 warn "next to in $after\n";#d#
330
331 # now or in the past already?
332 if ($after <= 0) {
333 $self->{_activity} = $NOW;
334
335 if ($self->{on_timeout}) {
336 $self->{on_timeout}->($self);
337 } else {
338 $! = Errno::ETIMEDOUT;
339 $self->error;
340 }
341
342 # callbakx could have changed timeout value, optimise
343 return unless $self->{timeout};
344
345 # calculate new after
346 $after = $self->{timeout};
347 }
348
349 Scalar::Util::weaken $self;
350
351 warn "after $after\n";#d#
352 $self->{_tw} ||= AnyEvent->timer (after => $after, cb => sub {
353 delete $self->{_tw};
354 $self->_timeout;
355 });
356 } else {
357 delete $self->{_tw};
358 }
359}
360
257############################################################################# 361#############################################################################
258 362
259=back 363=back
260 364
261=head2 WRITE QUEUE 365=head2 WRITE QUEUE
306 my $len = syswrite $self->{fh}, $self->{wbuf}; 410 my $len = syswrite $self->{fh}, $self->{wbuf};
307 411
308 if ($len >= 0) { 412 if ($len >= 0) {
309 substr $self->{wbuf}, 0, $len, ""; 413 substr $self->{wbuf}, 0, $len, "";
310 414
415 $self->{_activity} = time;
416
311 $self->{on_drain}($self) 417 $self->{on_drain}($self)
312 if $self->{low_water_mark} >= length $self->{wbuf} 418 if $self->{low_water_mark} >= length $self->{wbuf}
313 && $self->{on_drain}; 419 && $self->{on_drain};
314 420
315 delete $self->{_ww} unless length $self->{wbuf}; 421 delete $self->{_ww} unless length $self->{wbuf};
316 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAWOULDBLOCK) { 422 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
317 $self->error; 423 $self->error;
318 } 424 }
319 }; 425 };
320 426
321 # try to write data immediately 427 # try to write data immediately
378 sprintf "%d:%s,", (length $string), $string 484 sprintf "%d:%s,", (length $string), $string
379}; 485};
380 486
381=item json => $array_or_hashref 487=item json => $array_or_hashref
382 488
489Encodes the given hash or array reference into a JSON object. Unless you
490provide your own JSON object, this means it will be encoded to JSON text
491in UTF-8.
492
493JSON objects (and arrays) are self-delimiting, so you can write JSON at
494one end of a handle and read them at the other end without using any
495additional framing.
496
497The generated JSON text is guaranteed not to contain any newlines: While
498this module doesn't need delimiters after or between JSON texts to be
499able to read them, many other languages depend on that.
500
501A simple RPC protocol that interoperates easily with others is to send
502JSON arrays (or objects, although arrays are usually the better choice as
503they mimic how function argument passing works) and a newline after each
504JSON text:
505
506 $handle->push_write (json => ["method", "arg1", "arg2"]); # whatever
507 $handle->push_write ("\012");
508
509An AnyEvent::Handle receiver would simply use the C<json> read type and
510rely on the fact that the newline will be skipped as leading whitespace:
511
512 $handle->push_read (json => sub { my $array = $_[1]; ... });
513
514Other languages could read single lines terminated by a newline and pass
515this line into their JSON decoder of choice.
516
517=cut
518
519register_write_type json => sub {
520 my ($self, $ref) = @_;
521
522 require JSON;
523
524 $self->{json} ? $self->{json}->encode ($ref)
525 : JSON::encode_json ($ref)
526};
527
383=item AnyEvent::Handle::register_write_type type => $coderef->($self, @args) 528=item AnyEvent::Handle::register_write_type type => $coderef->($handle, @args)
384 529
385This function (not method) lets you add your own types to C<push_write>. 530This function (not method) lets you add your own types to C<push_write>.
386Whenever the given C<type> is used, C<push_write> will invoke the code 531Whenever the given C<type> is used, C<push_write> will invoke the code
387reference with the handle object and the remaining arguments. 532reference with the handle object and the remaining arguments.
388 533
628Predefined types are (if you have ideas for additional types, feel free to 773Predefined types are (if you have ideas for additional types, feel free to
629drop by and tell us): 774drop by and tell us):
630 775
631=over 4 776=over 4
632 777
633=item chunk => $octets, $cb->($self, $data) 778=item chunk => $octets, $cb->($handle, $data)
634 779
635Invoke the callback only once C<$octets> bytes have been read. Pass the 780Invoke the callback only once C<$octets> bytes have been read. Pass the
636data read to the callback. The callback will never be called with less 781data read to the callback. The callback will never be called with less
637data. 782data.
638 783
661 806
662sub unshift_read_chunk { 807sub unshift_read_chunk {
663 $_[0]->unshift_read (chunk => $_[1], $_[2]); 808 $_[0]->unshift_read (chunk => $_[1], $_[2]);
664} 809}
665 810
666=item line => [$eol, ]$cb->($self, $line, $eol) 811=item line => [$eol, ]$cb->($handle, $line, $eol)
667 812
668The callback will be called only once a full line (including the end of 813The callback will be called only once a full line (including the end of
669line marker, C<$eol>) has been read. This line (excluding the end of line 814line marker, C<$eol>) has been read. This line (excluding the end of line
670marker) will be passed to the callback as second argument (C<$line>), and 815marker) will be passed to the callback as second argument (C<$line>), and
671the end of line marker as the third argument (C<$eol>). 816the end of line marker as the third argument (C<$eol>).
708sub unshift_read_line { 853sub unshift_read_line {
709 my $self = shift; 854 my $self = shift;
710 $self->unshift_read (line => @_); 855 $self->unshift_read (line => @_);
711} 856}
712 857
713=item netstring => $cb->($string) 858=item netstring => $cb->($handle, $string)
714 859
715A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement). 860A netstring (http://cr.yp.to/proto/netstrings.txt, this is not an endorsement).
716 861
717Throws an error with C<$!> set to EBADMSG on format violations. 862Throws an error with C<$!> set to EBADMSG on format violations.
718 863
746 891
747 1 892 1
748 } 893 }
749}; 894};
750 895
751=item regex => $accept[, $reject[, $skip], $cb->($data) 896=item regex => $accept[, $reject[, $skip], $cb->($handle, $data)
752 897
753Makes a regex match against the regex object C<$accept> and returns 898Makes a regex match against the regex object C<$accept> and returns
754everything up to and including the match. 899everything up to and including the match.
755 900
756Example: read a single line terminated by '\n'. 901Example: read a single line terminated by '\n'.
817 962
818 () 963 ()
819 } 964 }
820}; 965};
821 966
967=item json => $cb->($handle, $hash_or_arrayref)
968
969Reads a JSON object or array, decodes it and passes it to the callback.
970
971If a C<json> object was passed to the constructor, then that will be used
972for the final decode, otherwise it will create a JSON coder expecting UTF-8.
973
974This read type uses the incremental parser available with JSON version
9752.09 (and JSON::XS version 2.2) and above. You have to provide a
976dependency on your own: this module will load the JSON module, but
977AnyEvent does not depend on it itself.
978
979Since JSON texts are fully self-delimiting, the C<json> read and write
980types are an ideal simple RPC protocol: just exchange JSON datagrams. See
981the C<json> write type description, above, for an actual example.
982
983=cut
984
985register_read_type json => sub {
986 my ($self, $cb, $accept, $reject, $skip) = @_;
987
988 require JSON;
989
990 my $data;
991 my $rbuf = \$self->{rbuf};
992
993 my $json = $self->{json} ||= JSON->new->utf8;
994
995 sub {
996 my $ref = $json->incr_parse ($self->{rbuf});
997
998 if ($ref) {
999 $self->{rbuf} = $json->incr_text;
1000 $json->incr_text = "";
1001 $cb->($self, $ref);
1002
1003 1
1004 } else {
1005 $self->{rbuf} = "";
1006 ()
1007 }
1008 }
1009};
1010
822=back 1011=back
823 1012
824=item AnyEvent::Handle::register_read_type type => $coderef->($self, $cb, @args) 1013=item AnyEvent::Handle::register_read_type type => $coderef->($handle, $cb, @args)
825 1014
826This function (not method) lets you add your own types to C<push_read>. 1015This function (not method) lets you add your own types to C<push_read>.
827 1016
828Whenever the given C<type> is used, C<push_read> will invoke the code 1017Whenever the given C<type> is used, C<push_read> will invoke the code
829reference with the handle object, the callback and the remaining 1018reference with the handle object, the callback and the remaining
831 1020
832The code reference is supposed to return a callback (usually a closure) 1021The code reference is supposed to return a callback (usually a closure)
833that works as a plain read callback (see C<< ->push_read ($cb) >>). 1022that works as a plain read callback (see C<< ->push_read ($cb) >>).
834 1023
835It should invoke the passed callback when it is done reading (remember to 1024It should invoke the passed callback when it is done reading (remember to
836pass C<$self> as first argument as all other callbacks do that). 1025pass C<$handle> as first argument as all other callbacks do that).
837 1026
838Note that this is a function, and all types registered this way will be 1027Note that this is a function, and all types registered this way will be
839global, so try to use unique names. 1028global, so try to use unique names.
840 1029
841For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>, 1030For examples, see the source of this module (F<perldoc -m AnyEvent::Handle>,
867 $self->{_rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub { 1056 $self->{_rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub {
868 my $rbuf = $self->{filter_r} ? \my $buf : \$self->{rbuf}; 1057 my $rbuf = $self->{filter_r} ? \my $buf : \$self->{rbuf};
869 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf; 1058 my $len = sysread $self->{fh}, $$rbuf, $self->{read_size} || 8192, length $$rbuf;
870 1059
871 if ($len > 0) { 1060 if ($len > 0) {
1061 $self->{_activity} = time;
1062
872 $self->{filter_r} 1063 $self->{filter_r}
873 ? $self->{filter_r}->($self, $rbuf) 1064 ? $self->{filter_r}->($self, $rbuf)
874 : $self->_drain_rbuf; 1065 : $self->_drain_rbuf;
875 1066
876 } elsif (defined $len) { 1067 } elsif (defined $len) {
877 delete $self->{_rw}; 1068 delete $self->{_rw};
1069 delete $self->{_ww};
1070 delete $self->{_tw};
878 $self->{_eof} = 1; 1071 $self->{_eof} = 1;
879 $self->_drain_rbuf; 1072 $self->_drain_rbuf;
880 1073
881 } elsif ($! != EAGAIN && $! != EINTR && $! != &AnyEvent::Util::WSAWOULDBLOCK) { 1074 } elsif ($! != EAGAIN && $! != EINTR && $! != WSAEWOULDBLOCK) {
882 return $self->error; 1075 return $self->error;
883 } 1076 }
884 }); 1077 });
885 } 1078 }
886} 1079}

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines