IO::Async::Stream(3) User Contributed Perl Documentation IO::Async::Stream(3)NAME
"IO::Async::Stream" - read and write buffers around an IO handle
SYNOPSIS
use IO::Socket::INET;
use IO::Async::Stream;
use IO::Async::Loop;
my $loop = IO::Async::Loop->new();
my $socket = IO::Socket::INET->new(
PeerHost => "some.other.host",
PeerPort => 12345,
Blocking => 0, # This line is very important
);
my $stream = IO::Async::Stream->new(
handle => $socket,
on_read => sub {
my ( $self, $buffref, $closed ) = @_;
if( $$buffref =~ s/^(.*\n)// ) {
print "Received a line $1";
return 1;
}
if( $closed ) {
print "Closed; last partial line is $$buffref\n";
}
return 0;
}
);
$stream->write( "An initial line here\n" );
Or
my $record_stream = IO::Async::Stream->new(
handle => ...,
on_read => sub {
my ( $self, $buffref, $closed ) = @_;
if( length $$buffref >= 16 ) {
my $record = substr( $$buffref, 0, 16, "" );
print "Received a 16-byte record: $record\n";
return 1;
}
if( $closed and length $$buffref ) {
print "Closed: a partial record still exists\n";
}
return 0;
}
);
Or
use IO::Handle;
my $stream = IO::Async::Stream->new(
read_handle => \*STDIN,
write_handle => \*STDOUT,
...
);
DESCRIPTION
This module provides a subclass of "IO::Async::Handle" which implements
asynchronous communications buffers around stream handles. It provides
buffering for both incoming and outgoing data, which are transferred to
or from the actual OS-level filehandle as controlled by the containing
Loop.
Data can be added to the outgoing buffer at any time using the
"write()" method, and will be flushed whenever the underlying handle is
notified as being write-ready. Whenever the handle is notified as being
read-ready, the data is read in from the handle, and the "on_read" code
is called to indicate the data is available. The code can then inspect
the buffer and possibly consume any input it considers ready.
This object may be used in one of two ways; with a callback function,
or as a base class.
Callbacks
If certain keys are supplied to the constructor, they should
contain CODE references to callback functions that will be called
in the following manner:
$ret = $on_read->( $self, \$buffer, $handleclosed )
$on_read_error->( $self, $errno )
$on_outgoing_empty->( $self )
$on_write_error->( $self, $errno )
A reference to the calling "IO::Async::Stream" object is passed as
the first argument, so that the callback can access it.
Base Class
If a subclass is built, then it can override the "on_read" or
"on_outgoing_empty" methods, which will be called in the following
manner:
$ret = $self->on_read( \$buffer, $handleclosed )
$self->on_read_error( $errno )
$self->on_outgoing_empty()
$self->on_write_error( $errno )
The first argument to the "on_read()" callback is a reference to a
plain perl string. The code should inspect and remove any data it
likes, but is not required to remove all, or indeed any of the data.
Any data remaining in the buffer will be preserved for the next call,
the next time more data is received from the handle.
In this way, it is easy to implement code that reads records of some
form when completed, but ignores partially-received records, until all
the data is present. If the method is confident no more useful data
remains, it should return 0. If not, it should return 1, and the method
will be called again. This makes it easy to implement code that handles
multiple incoming records at the same time. See the examples at the end
of this documentation for more detail.
The second argument to the "on_read()" method is a scalar indicating
whether the handle has been closed. Normally it is false, but will
become true once the handle closes. A reference to the buffer is passed
to the method in the usual way, so it may inspect data contained in it.
Once the method returns a false value, it will not be called again, as
the handle is now closed and no more data can arrive.
The "on_read()" code may also dynamically replace itself with a new
callback by returning a CODE reference instead of 0 or 1. The original
callback or method that the object first started with may be restored
by returning "undef". Whenever the callback is changed in this way, the
new code is called again; even if the read buffer is currently empty.
See the examples at the end of this documentation for more detail.
The "on_read_error" and "on_write_error" callbacks are passed the value
of $! at the time the error occured. (The $! variable itself, by its
nature, may have changed from the original error by the time this
callback runs so it should always use the value passed in).
If an error occurs when the corresponding error callback is not
supplied, and there is not a subclass method for it, then the "close()"
method is called instead.
The "on_outgoing_empty" callback is not passed any arguments.
PARAMETERS
The following named parameters may be passed to "new" or "configure":
read_handle => IO
The IO handle to read from. Must implement "fileno" and
"sysread" methods.
write_handle => IO
The IO handle to write to. Must implement "fileno" and
"syswrite" methods.
handle => IO
Shortcut to specifying the same IO handle for both of the
above.
on_read => CODE
A CODE reference for when more data is available in the
internal receiving buffer.
on_read_error => CODE
A CODE reference for when the "sysread()" method on the read
handle fails.
on_outgoing_empty => CODE
A CODE reference for when the writing data buffer becomes
empty.
on_write_error => CODE
A CODE reference for when the "syswrite()" method on the write
handle fails.
autoflush => BOOL
Optional. If true, the "write" method will attempt to write
data to the operating system immediately, without waiting for
the loop to indicate the filehandle is write-ready. This is
useful, for example, on streams that should contain up-to-date
logging or console information.
It currently defaults to false for any file handle, but future
versions of "IO::Async" may enable this by default on STDOUT
and STDERR.
read_all => BOOL
Optional. If true, attempt to read as much data from the kernel
as possible when the handle becomes readable. By default this
is turned off, meaning at most a fixed-size buffer of 8 KiB is
read. If there is still more data in the kernel's buffer, the
handle will still be readable, and will be read from again.
This behaviour allows multiple streams to be multiplexed
simultaneously, meaning that a large bulk transfer on one
stream cannot starve other filehandles of processing time.
Turning this option on may improve bulk data transfer rate, at
the risk of delaying or stalling processing on other
filehandles.
write_all => BOOL
Optional. Analogous to the "read_all" option, but for writing
to filehandles into the kernel buffer. When "autoflush" is
enabled, option only affects deferred writing if the initial
attempt failed due to buffer space.
If a read handle is given, it is required that either an "on_read"
callback reference is passed, or that the object provides an "on_read"
method. It is optional whether either is true for "on_outgoing_empty";
if neither is supplied then no action will be taken when the writing
buffer becomes empty.
An "on_read" callback may be supplied even if no read handle is yet
given, to be used when a read handle is eventually provided by the
"set_handles" method.
METHODS
$stream->close
A synonym for "close_when_empty". This should not be used when the
deferred wait behaviour is required, as the behaviour of "close" may
change in a future version of "IO::Async". Instead, call
"close_when_empty" directly.
$stream->close_when_empty
If the write buffer is empty, this method calls "close" on the
underlying IO handles, and removes the stream from its containing loop.
If the write buffer still contains data, then this is deferred until
the buffer is empty. This is intended for "write-then-close" one-shot
streams.
$stream->write( "Here is my final data\n" );
$stream->close_when_empty;
Because of this deferred nature, it may not be suitable for error
handling. See instead the "close_now" method.
$stream->close_now
This method immediately closes the underlying IO handles and removes
the stream from the containing loop. It will not wait to flush the
remaining data in the write buffer.
$stream->write( $data )
This method adds data to the outgoing data queue. The data is not yet
sent to the handle; this will be done later in the "on_write_ready()"
method.
$data A scalar containing data to write
If the "autoflush" option is set, this method will try immediately to
write the data to the underlying filehandle. If this completes
successfully then it will have been written by the time this method
returns. If it fails to write completely, then the data is queued as if
"autoflush" were not set, and will be flushed later as normal by the
"on_write_ready()" method.
EXAMPLES
A line-based "on_read()" method
The following "on_read()" method accepts incoming "\n"-terminated lines
and prints them to the program's "STDOUT" stream.
sub on_read
{
my $self = shift;
my ( $buffref, $handleclosed ) = @_;
if( $$buffref =~ s/^(.*\n)// ) {
print "Received a line: $1";
return 1;
}
return 0;
}
Because a reference to the buffer itself is passed, it is simple to use
a "s///" regular expression on the scalar it points at, to both check
if data is ready (i.e. a whole line), and to remove it from the buffer.
If no data is available then 0 is returned, to indicate it should not
be tried again. If a line was successfully extracted, then 1 is
returned, to indicate it should try again in case more lines exist in
the buffer.
Dynamic replacement of "on_read()"
Consider the following protocol (inspired by IMAP), which consists of
"\n"-terminated lines that may have an optional data block attached.
The presence of such a data block, as well as its size, is indicated by
the line prefix.
sub on_read
{
my $self = shift;
my ( $buffref, $handleclosed ) = @_;
if( $$buffref =~ s/^DATA (\d+):(.*)\n// ) {
my $length = $1;
my $line = $2;
return sub {
my $self = shift;
my ( $buffref, $handleclosed ) = @_;
return 0 unless length $$buffref >= $length;
# Take and remove the data from the buffer
my $data = substr( $$buffref, 0, $length, "" );
print "Received a line $line with some data ($data)\n";
return undef; # Restore the original method
}
}
elsif( $$buffref =~ s/^LINE:(.*)\n// ) {
my $line = $1;
print "Received a line $line with no data\n";
return 1;
}
else {
print STDERR "Unrecognised input\n";
# Handle it somehow
}
}
In the case where trailing data is supplied, a new temporary
"on_read()" callback is provided in a closure. This closure captures
the $length variable so it knows how much data to expect. It also
captures the $line variable so it can use it in the event report. When
this method has finished reading the data, it reports the event, then
restores the original method by returning "undef".
SEE ALSO
ยท IO::Handle - Supply object methods for I/O handles
AUTHOR
Paul Evans <leonerd@leonerd.org.uk>
perl v5.14.2 2010-06-09 IO::Async::Stream(3)