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.6 by elmex, Mon Apr 28 09:27:47 2008 UTC vs.
Revision 1.10 by root, Sat May 3 12:17:35 2008 UTC

1package AnyEvent::Handle; 1package AnyEvent::Handle;
2 2
3no warnings; 3no warnings;
4use strict; 4use strict;
5 5
6use AnyEvent; 6use AnyEvent ();
7use IO::Handle; 7use AnyEvent::Util ();
8use Scalar::Util ();
9use Carp ();
10use Fcntl ();
8use Errno qw/EAGAIN EINTR/; 11use Errno qw/EAGAIN EINTR/;
9 12
10=head1 NAME 13=head1 NAME
11 14
12AnyEvent::Handle - non-blocking I/O on filehandles via AnyEvent 15AnyEvent::Handle - non-blocking I/O on filehandles via AnyEvent
13 16
14=head1 VERSION
15
16Version 0.01
17
18=cut 17=cut
19 18
20our $VERSION = '0.01'; 19our $VERSION = '0.02';
21 20
22=head1 SYNOPSIS 21=head1 SYNOPSIS
23 22
24 use AnyEvent; 23 use AnyEvent;
25 use AnyEvent::Handle; 24 use AnyEvent::Handle;
26 25
27 my $cv = AnyEvent->condvar; 26 my $cv = AnyEvent->condvar;
28 27
29 my $ae_fh = AnyEvent::Handle->new (fh => \*STDIN); 28 my $ae_fh = AnyEvent::Handle->new (fh => \*STDIN);
30 29
31 $ae_fh->on_eof (sub { $cv->broadcast }); 30 #TODO
32
33 $ae_fh->readlines (sub {
34 my ($ae_fh, @lines) = @_;
35 for (@lines) {
36 chomp;
37 print "Line: $_";
38 }
39 });
40 31
41 # or use the constructor to pass the callback: 32 # or use the constructor to pass the callback:
42 33
43 my $ae_fh2 = 34 my $ae_fh2 =
44 AnyEvent::Handle->new ( 35 AnyEvent::Handle->new (
45 fh => \*STDIN, 36 fh => \*STDIN,
46 on_eof => sub { 37 on_eof => sub {
47 $cv->broadcast; 38 $cv->broadcast;
48 }, 39 },
49 on_readline => sub { 40 #TODO
50 my ($ae_fh, @lines) = @_; 41 );
51 for (@lines) { 42
52 chomp; 43 $cv->wait;
53 print "Line: $_"; 44
45=head1 DESCRIPTION
46
47This module is a helper module to make it easier to do event-based I/O on
48filehandles (and sockets, see L<AnyEvent::Socket> for an easy way to make
49non-blocking resolves and connects).
50
51In the following, when the documentation refers to of "bytes" then this
52means characters. As sysread and syswrite are used for all I/O, their
53treatment of characters applies to this module as well.
54
55All callbacks will be invoked with the handle object as their first
56argument.
57
58=head1 METHODS
59
60=over 4
61
62=item B<new (%args)>
63
64The constructor supports these arguments (all as key => value pairs).
65
66=over 4
67
68=item fh => $filehandle [MANDATORY]
69
70The filehandle this L<AnyEvent::Handle> object will operate on.
71
72NOTE: The filehandle will be set to non-blocking (using
73AnyEvent::Util::fh_nonblocking).
74
75=item on_eof => $cb->($self) [MANDATORY]
76
77Set the callback to be called on EOF.
78
79=item on_error => $cb->($self)
80
81This is the fatal error callback, that is called when, well, a fatal error
82ocurs, such as not being able to resolve the hostname, failure to connect
83or a read error.
84
85The object will not be in a usable state when this callback has been
86called.
87
88On callback entrance, the value of C<$!> contains the operating system
89error (or C<ENOSPC> or C<EPIPE>).
90
91While not mandatory, it is I<highly> recommended to set this callback, as
92you will not be notified of errors otherwise. The default simply calls
93die.
94
95=item on_read => $cb->($self)
96
97This sets the default read callback, which is called when data arrives
98and no read request is in the queue.
99
100To access (and remove data from) the read buffer, use the C<< ->rbuf >>
101method or acces sthe C<$self->{rbuf}> member directly.
102
103When an EOF condition is detected then AnyEvent::Handle will first try to
104feed all the remaining data to the queued callbacks and C<on_read> before
105calling the C<on_eof> callback. If no progress can be made, then a fatal
106error will be raised (with C<$!> set to C<EPIPE>).
107
108=item on_drain => $cb->()
109
110This sets the callback that is called when the write buffer becomes empty
111(or when the callback is set and the buffer is empty already).
112
113To append to the write buffer, use the C<< ->push_write >> method.
114
115=item rbuf_max => <bytes>
116
117If defined, then a fatal error will be raised (with C<$!> set to C<ENOSPC>)
118when the read buffer ever (strictly) exceeds this size. This is useful to
119avoid denial-of-service attacks.
120
121For example, a server accepting connections from untrusted sources should
122be configured to accept only so-and-so much data that it cannot act on
123(for example, when expecting a line, an attacker could send an unlimited
124amount of data without a callback ever being called as long as the line
125isn't finished).
126
127=item read_size => <bytes>
128
129The default read block size (the amount of bytes this module will try to read
130on each [loop iteration). Default: C<4096>.
131
132=item low_water_mark => <bytes>
133
134Sets the amount of bytes (default: C<0>) that make up an "empty" write
135buffer: If the write reaches this size or gets even samller it is
136considered empty.
137
138=back
139
140=cut
141
142sub new {
143 my $class = shift;
144
145 my $self = bless { @_ }, $class;
146
147 $self->{fh} or Carp::croak "mandatory argument fh is missing";
148
149 AnyEvent::Util::fh_nonblocking $self->{fh}, 1;
150
151 $self->on_eof ((delete $self->{on_eof} ) or Carp::croak "mandatory argument on_eof is missing");
152
153 $self->on_error (delete $self->{on_error}) if $self->{on_error};
154 $self->on_drain (delete $self->{on_drain}) if $self->{on_drain};
155 $self->on_read (delete $self->{on_read} ) if $self->{on_read};
156
157 $self->start_read;
158
159 $self
160}
161
162sub _shutdown {
163 my ($self) = @_;
164
165 delete $self->{rw};
166 delete $self->{ww};
167 delete $self->{fh};
168}
169
170sub error {
171 my ($self) = @_;
172
173 {
174 local $!;
175 $self->_shutdown;
176 }
177
178 if ($self->{on_error}) {
179 $self->{on_error}($self);
180 } else {
181 die "AnyEvent::Handle uncaught fatal error: $!";
182 }
183}
184
185=item $fh = $handle->fh
186
187This method returns the filehandle of the L<AnyEvent::Handle> object.
188
189=cut
190
191sub fh { $_[0]->{fh} }
192
193=item $handle->on_error ($cb)
194
195Replace the current C<on_error> callback (see the C<on_error> constructor argument).
196
197=cut
198
199sub on_error {
200 $_[0]{on_error} = $_[1];
201}
202
203=item $handle->on_eof ($cb)
204
205Replace the current C<on_eof> callback (see the C<on_eof> constructor argument).
206
207=cut
208
209sub on_eof {
210 $_[0]{on_eof} = $_[1];
211}
212
213#############################################################################
214
215=back
216
217=head2 WRITE QUEUE
218
219AnyEvent::Handle manages two queues per handle, one for writing and one
220for reading.
221
222The write queue is very simple: you can add data to its end, and
223AnyEvent::Handle will automatically try to get rid of it for you.
224
225When data could be writtena nd the write buffer is shorter then the low
226water mark, the C<on_drain> callback will be invoked.
227
228=over 4
229
230=item $handle->on_drain ($cb)
231
232Sets the C<on_drain> callback or clears it (see the description of
233C<on_drain> in the constructor).
234
235=cut
236
237sub on_drain {
238 my ($self, $cb) = @_;
239
240 $self->{on_drain} = $cb;
241
242 $cb->($self)
243 if $cb && $self->{low_water_mark} >= length $self->{wbuf};
244}
245
246=item $handle->push_write ($data)
247
248Queues the given scalar to be written. You can push as much data as you
249want (only limited by the available memory), as C<AnyEvent::Handle>
250buffers it independently of the kernel.
251
252=cut
253
254sub push_write {
255 my ($self, $data) = @_;
256
257 $self->{wbuf} .= $data;
258
259 unless ($self->{ww}) {
260 Scalar::Util::weaken $self;
261 my $cb = sub {
262 my $len = syswrite $self->{fh}, $self->{wbuf};
263
264 if ($len > 0) {
265 substr $self->{wbuf}, 0, $len, "";
266
267
268 $self->{on_drain}($self)
269 if $self->{low_water_mark} >= length $self->{wbuf}
270 && $self->{on_drain};
271
272 delete $self->{ww} unless length $self->{wbuf};
273 } elsif ($! != EAGAIN && $! != EINTR) {
274 $self->error;
275 }
276 };
277
278 $self->{ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $cb);
279
280 $cb->($self);
281 };
282}
283
284#############################################################################
285
286=back
287
288=head2 READ QUEUE
289
290AnyEvent::Handle manages two queues per handle, one for writing and one
291for reading.
292
293The read queue is more complex than the write queue. It can be used in two
294ways, the "simple" way, using only C<on_read> and the "complex" way, using
295a queue.
296
297In the simple case, you just install an C<on_read> callback and whenever
298new data arrives, it will be called. You can then remove some data (if
299enough is there) from the read buffer (C<< $handle->rbuf >>) if you want
300or not.
301
302In the more complex case, you want to queue multiple callbacks. In this
303case, AnyEvent::Handle will call the first queued callback each time new
304data arrives and removes it when it has done its job (see C<push_read>,
305below).
306
307This way you can, for example, push three line-reads, followed by reading
308a chunk of data, and AnyEvent::Handle will execute them in order.
309
310Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by
311the specified number of bytes which give an XML datagram.
312
313 # in the default state, expect some header bytes
314 $handle->on_read (sub {
315 # some data is here, now queue the length-header-read (4 octets)
316 shift->unshift_read_chunk (4, sub {
317 # header arrived, decode
318 my $len = unpack "N", $_[1];
319
320 # now read the payload
321 shift->unshift_read_chunk ($len, sub {
322 my $xml = $_[1];
323 # handle xml
324 });
325 });
326 });
327
328Example 2: Implement a client for a protocol that replies either with
329"OK" and another line or "ERROR" for one request, and 64 bytes for the
330second request. Due tot he availability of a full queue, we can just
331pipeline sending both requests and manipulate the queue as necessary in
332the callbacks:
333
334 # request one
335 $handle->push_write ("request 1\015\012");
336
337 # we expect "ERROR" or "OK" as response, so push a line read
338 $handle->push_read_line (sub {
339 # if we got an "OK", we have to _prepend_ another line,
340 # so it will be read before the second request reads its 64 bytes
341 # which are already in the queue when this callback is called
342 # we don't do this in case we got an error
343 if ($_[1] eq "OK") {
344 $_[0]->unshift_read_line (sub {
345 my $response = $_[1];
346 ...
347 });
348 }
349 });
350
351 # request two
352 $handle->push_write ("request 2\015\012");
353
354 # simply read 64 bytes, always
355 $handle->push_read_chunk (64, sub {
356 my $response = $_[1];
357 ...
358 });
359
360=over 4
361
362=cut
363
364sub _drain_rbuf {
365 my ($self) = @_;
366
367 return if exists $self->{in_drain};
368 local $self->{in_drain} = 1;
369
370 while (my $len = length $self->{rbuf}) {
371 no strict 'refs';
372 if (my $cb = shift @{ $self->{queue} }) {
373 if (!$cb->($self)) {
374 if ($self->{eof}) {
375 # no progress can be made (not enough data and no data forthcoming)
376 $! = &Errno::EPIPE; return $self->error;
54 } 377 }
378
379 unshift @{ $self->{queue} }, $cb;
380 return;
55 } 381 }
56 );
57
58 $cv->wait;
59
60=head1 DESCRIPTION
61
62This module is a helper module to make it easier to do non-blocking I/O
63on filehandles (and sockets, see L<AnyEvent::Socket>).
64
65The event loop is provided by L<AnyEvent>.
66
67=head1 METHODS
68
69=over 4
70
71=item B<new (%args)>
72
73The constructor has these arguments:
74
75=over 4
76
77=item fh => $filehandle
78
79The filehandle this L<AnyEvent::Handle> object will operate on.
80
81NOTE: The filehandle will be set to non-blocking.
82
83=item read_block_size => $size
84
85The default read block size use for reads via the C<on_read>
86method.
87
88=item on_read => $cb
89
90=item on_eof => $cb
91
92=item on_error => $cb
93
94These are shortcuts, that will call the corresponding method and set the callback to C<$cb>.
95
96=item on_readline => $cb
97
98The C<readlines> method is called with the default seperator and C<$cb> as callback
99for you.
100
101=back
102
103=cut
104
105sub new {
106 my $this = shift;
107 my $class = ref($this) || $this;
108 my $self = {
109 read_block_size => 4096,
110 rbuf => '',
111 @_
112 };
113 bless $self, $class;
114
115 $self->{fh}->blocking (0) if $self->{fh};
116
117 if ($self->{on_read}) {
118 $self->on_read ($self->{on_read});
119
120 } elsif ($self->{on_readline}) { 382 } elsif ($self->{on_read}) {
121 $self->readlines ($self->{on_readline}); 383 $self->{on_read}($self);
122 384
123 } elsif ($self->{on_eof}) { 385 if (
124 $self->on_eof ($self->{on_eof}); 386 $self->{eof} # if no further data will arrive
125 387 && $len == length $self->{rbuf} # and no data has been consumed
126 } elsif ($self->{on_error}) { 388 && !@{ $self->{queue} } # and the queue is still empty
127 $self->on_eof ($self->{on_error}); 389 && $self->{on_read} # and we still want to read data
390 ) {
391 # then no progress can be made
392 $! = &Errno::EPIPE; return $self->error;
393 }
394 } else {
395 # read side becomes idle
396 delete $self->{rw};
397 return;
398 }
128 } 399 }
129 400
130 return $self 401 if ($self->{eof}) {
402 $self->_shutdown;
403 $self->{on_eof}($self);
404 }
131} 405}
132 406
133=item B<fh> 407=item $handle->on_read ($cb)
134 408
135This method returns the filehandle of the L<AnyEvent::Handle> object. 409This replaces the currently set C<on_read> callback, or clears it (when
136 410the new callback is C<undef>). See the description of C<on_read> in the
137=cut 411constructor.
138
139sub fh { $_[0]->{fh} }
140
141=item B<on_read ($callback)>
142
143This method installs a C<$callback> that will be called
144when new data arrived. You can access the read buffer via the C<rbuf>
145method (see below).
146
147The first argument of the C<$callback> will be the L<AnyEvent::Handle> object.
148 412
149=cut 413=cut
150 414
151sub on_read { 415sub on_read {
152 my ($self, $cb) = @_; 416 my ($self, $cb) = @_;
417
153 $self->{on_read} = $cb; 418 $self->{on_read} = $cb;
419}
154 420
155 unless (defined $self->{on_read}) { 421=item $handle->rbuf
156 delete $self->{on_read_w}; 422
157 return; 423Returns the read buffer (as a modifiable lvalue).
424
425You can access the read buffer directly as the C<< ->{rbuf} >> member, if
426you want.
427
428NOTE: The read buffer should only be used or modified if the C<on_read>,
429C<push_read> or C<unshift_read> methods are used. The other read methods
430automatically manage the read buffer.
431
432=cut
433
434sub rbuf : lvalue {
435 $_[0]{rbuf}
436}
437
438=item $handle->push_read ($cb)
439
440=item $handle->unshift_read ($cb)
441
442Append the given callback to the end of the queue (C<push_read>) or
443prepend it (C<unshift_read>).
444
445The callback is called each time some additional read data arrives.
446
447It must check wether enough data is in the read buffer already.
448
449If not enough data is available, it must return the empty list or a false
450value, in which case it will be called repeatedly until enough data is
451available (or an error condition is detected).
452
453If enough data was available, then the callback must remove all data it is
454interested in (which can be none at all) and return a true value. After returning
455true, it will be removed from the queue.
456
457=cut
458
459sub push_read {
460 my ($self, $cb) = @_;
461
462 push @{ $self->{queue} }, $cb;
463 $self->_drain_rbuf;
464}
465
466sub unshift_read {
467 my ($self, $cb) = @_;
468
469 push @{ $self->{queue} }, $cb;
470 $self->_drain_rbuf;
471}
472
473=item $handle->push_read_chunk ($len, $cb->($self, $data))
474
475=item $handle->unshift_read_chunk ($len, $cb->($self, $data))
476
477Append the given callback to the end of the queue (C<push_read_chunk>) or
478prepend it (C<unshift_read_chunk>).
479
480The callback will be called only once C<$len> bytes have been read, and
481these C<$len> bytes will be passed to the callback.
482
483=cut
484
485sub _read_chunk($$) {
486 my ($self, $len, $cb) = @_;
487
488 sub {
489 $len <= length $_[0]{rbuf} or return;
490 $cb->($self, $_[0], substr $_[0]{rbuf}, 0, $len, "");
491 1
158 } 492 }
159 493}
160 $self->{on_read_w} = 494
161 AnyEvent->io (poll => 'r', fh => $self->{fh}, cb => sub { 495sub push_read_chunk {
162 #d# warn "READ:[$self->{read_size}] $self->{read_block_size} : ".length ($self->{rbuf})."\n"; 496 $_[0]->push_read (&_read_chunk);
163 my $rbuf_len = length $self->{rbuf}; 497}
164 my $l; 498
165 if (defined $self->{read_size}) { 499
166 $l = sysread $self->{fh}, $self->{rbuf}, 500sub unshift_read_chunk {
167 ($self->{read_size} - $rbuf_len), $rbuf_len; 501 $_[0]->unshift_read (&_read_chunk);
168 } else { 502}
503
504=item $handle->push_read_line ([$eol, ]$cb->($self, $line, $eol))
505
506=item $handle->unshift_read_line ([$eol, ]$cb->($self, $line, $eol))
507
508Append the given callback to the end of the queue (C<push_read_line>) or
509prepend it (C<unshift_read_line>).
510
511The callback will be called only once a full line (including the end of
512line marker, C<$eol>) has been read. This line (excluding the end of line
513marker) will be passed to the callback as second argument (C<$line>), and
514the end of line marker as the third argument (C<$eol>).
515
516The end of line marker, C<$eol>, can be either a string, in which case it
517will be interpreted as a fixed record end marker, or it can be a regex
518object (e.g. created by C<qr>), in which case it is interpreted as a
519regular expression.
520
521The end of line marker argument C<$eol> is optional, if it is missing (NOT
522undef), then C<qr|\015?\012|> is used (which is good for most internet
523protocols).
524
525Partial lines at the end of the stream will never be returned, as they are
526not marked by the end of line marker.
527
528=cut
529
530sub _read_line($$) {
531 my $self = shift;
532 my $cb = pop;
533 my $eol = @_ ? shift : qr|(\015?\012)|;
534 my $pos;
535
536 $eol = qr|(\Q$eol\E)| unless ref $eol;
537 $eol = qr|^(.*?)($eol)|;
538
539 sub {
540 $_[0]{rbuf} =~ s/$eol// or return;
541
542 $cb->($self, $1, $2);
543 1
544 }
545}
546
547sub push_read_line {
548 $_[0]->push_read (&_read_line);
549}
550
551sub unshift_read_line {
552 $_[0]->unshift_read (&_read_line);
553}
554
555=item $handle->stop_read
556
557=item $handle->start_read
558
559In rare cases you actually do not want to read anything form the
560socket. In this case you can call C<stop_read>. Neither C<on_read> no
561any queued callbacks will be executed then. To start readign again, call
562C<start_read>.
563
564=cut
565
566sub stop_read {
567 my ($self) = @_;
568
569 delete $self->{rw};
570}
571
572sub start_read {
573 my ($self) = @_;
574
575 unless ($self->{rw} || $self->{eof}) {
576 Scalar::Util::weaken $self;
577
578 $self->{rw} = AnyEvent->io (fh => $self->{fh}, poll => "r", cb => sub {
169 $l = sysread $self->{fh}, $self->{rbuf}, $self->{read_block_size}, $rbuf_len; 579 my $len = sysread $self->{fh}, $self->{rbuf}, $self->{read_size} || 8192, length $self->{rbuf};
580
581 if ($len > 0) {
582 if (exists $self->{rbuf_max}) {
583 if ($self->{rbuf_max} < length $self->{rbuf}) {
584 $! = &Errno::ENOSPC; return $self->error;
585 }
586 }
587
588 } elsif (defined $len) {
589 $self->{eof} = 1;
590 delete $self->{rw};
591
592 } elsif ($! != EAGAIN && $! != EINTR) {
593 return $self->error;
170 } 594 }
171 #d# warn "READL $l [$self->{rbuf}]\n";
172 595
173 if (not defined $l) { 596 $self->_drain_rbuf;
174 return if $! == EAGAIN || $! == EINTR;
175 $self->{on_error}->($self) if $self->{on_error};
176 delete $self->{on_read_w};
177
178 } elsif ($l == 0) {
179 $self->{on_eof}->($self) if $self->{on_eof};
180 delete $self->{on_read_w};
181
182 } else {
183 $self->{on_read}->($self);
184 }
185 }); 597 });
186}
187
188=item B<on_error ($callback)>
189
190Whenever a read or write operation resulted in an error the C<$callback>
191will be called.
192
193The first argument of C<$callback> will be the L<AnyEvent::Handle> object itself.
194The error is given as errno in C<$!>.
195
196=cut
197
198sub on_error {
199 $_[0]->{on_error} = $_[1];
200}
201
202=item B<on_eof ($callback)>
203
204Installs the C<$callback> that will be called when the end of file is
205encountered in a read operation this C<$callback> will be called. The first
206argument will be the L<AnyEvent::Handle> object itself.
207
208=cut
209
210sub on_eof {
211 $_[0]->{on_eof} = $_[1];
212}
213
214=item B<rbuf>
215
216Returns a reference to the read buffer.
217
218NOTE: The read buffer should only be used or modified if the C<on_read>
219method is used directly. The C<read> and C<readlines> methods will provide
220the read data to their callbacks.
221
222=cut
223
224sub rbuf : lvalue {
225 $_[0]->{rbuf}
226}
227
228=item B<read ($len, $callback)>
229
230Will read exactly C<$len> bytes from the filehandle and call the C<$callback>
231if done so. The first argument to the C<$callback> will be the L<AnyEvent::Handle>
232object itself and the second argument the read data.
233
234NOTE: This method will override any callbacks installed via the C<on_read> method.
235
236=cut
237
238sub read {
239 my ($self, $len, $cb) = @_;
240
241 $self->{read_cb} = $cb;
242 my $old_blk_size = $self->{read_block_size};
243 $self->{read_block_size} = $len;
244
245 $self->on_read (sub {
246 #d# warn "OFOFO $len || ".length($_[0]->{rbuf})."||\n";
247
248 if ($len == length $_[0]->{rbuf}) {
249 $_[0]->{read_block_size} = $old_blk_size;
250 $_[0]->on_read (undef);
251 $_[0]->{read_cb}->($_[0], (substr $self->{rbuf}, 0, $len, ''));
252 }
253 });
254}
255
256=item B<readlines ($callback)>
257
258=item B<readlines ($sep, $callback)>
259
260This method will read lines from the filehandle, seperated by C<$sep> or C<"\n">
261if C<$sep> is not provided. C<$sep> will be used as "line" seperator.
262
263The C<$callback> will be called when at least one
264line could be read. The first argument to the C<$callback> will be the L<AnyEvent::Handle>
265object itself and the rest of the arguments will be the read lines.
266
267NOTE: This method will override any callbacks installed via the C<on_read> method.
268
269=cut
270
271sub readlines {
272 my ($self, $sep, $cb) = @_;
273
274 if (ref $sep) {
275 $cb = $sep;
276 $sep = "\n";
277
278 } elsif (not defined $sep) {
279 $sep = "\n";
280 } 598 }
281
282 my $sep_len = length $sep;
283
284 $self->{on_readline} = $cb;
285
286 $self->on_read (sub {
287 my @lines;
288 my $rb = \$_[0]->{rbuf};
289 my $pos;
290 while (($pos = index ($$rb, $sep)) >= 0) {
291 push @lines, substr $$rb, 0, $pos + $sep_len, '';
292 }
293 $self->{on_readline}->($_[0], @lines);
294 });
295}
296
297=item B<write ($data)>
298
299=item B<write ($callback)>
300
301=item B<write ($data, $callback)>
302
303This method will write C<$data> to the filehandle and call the C<$callback>
304afterwards. If only C<$callback> is provided it will be called when the
305write buffer becomes empty the next time (or immediately if it already is empty).
306
307=cut
308
309sub write {
310 my ($self, $data, $cb) = @_;
311 if (ref $data) { $cb = $data; undef $data }
312 push @{$self->{write_bufs}}, [$data, $cb];
313 $self->_check_writer;
314}
315
316sub _check_writer {
317 my ($self) = @_;
318
319 if ($self->{write_w}) {
320 unless ($self->{write_cb}) {
321 while (@{$self->{write_bufs}} && not defined $self->{write_bufs}->[0]->[1]) {
322 my $wba = shift @{$self->{write_bufs}};
323 $self->{wbuf} .= $wba->[0];
324 }
325 }
326 return;
327 }
328
329 my $wba = shift @{$self->{write_bufs}}
330 or return;
331
332 unless (defined $wba->[0]) {
333 $wba->[1]->($self) if $wba->[1];
334 $self->_check_writer;
335 return;
336 }
337
338 $self->{wbuf} = $wba->[0];
339 $self->{write_cb} = $wba->[1];
340
341 $self->{write_w} =
342 AnyEvent->io (poll => 'w', fh => $self->{fh}, cb => sub {
343 my $l = syswrite $self->{fh}, $self->{wbuf}, length $self->{wbuf};
344
345 if (not defined $l) {
346 return if $! == EAGAIN || $! == EINTR;
347 delete $self->{write_w};
348 $self->{on_error}->($self) if $self->{on_error};
349
350 } else {
351 substr $self->{wbuf}, 0, $l, '';
352
353 if (length ($self->{wbuf}) == 0) {
354 $self->{write_cb}->($self) if $self->{write_cb};
355
356 delete $self->{write_w};
357 delete $self->{wbuf};
358 delete $self->{write_cb};
359
360 $self->_check_writer;
361 }
362 }
363 });
364} 599}
365 600
366=back 601=back
367 602
368=head1 AUTHOR 603=head1 AUTHOR
369 604
370Robin Redeker, C<< <elmex at ta-sa.org> >> 605Robin Redeker C<< <elmex at ta-sa.org> >>, Marc Lehmann <schmorp@schmorp.de>.
371 606
372=cut 607=cut
373 608
3741; # End of AnyEvent::Handle 6091; # End of AnyEvent::Handle

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines