The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

IO::Async::Protocol::Stream - base class for stream-based protocols

SYNOPSIS

Most likely this class will be subclassed to implement a particular network protocol.

 package Net::Async::HelloWorld;

 use strict;
 use warnings;
 use base qw( IO::Async::Protocol::Stream );

 sub on_read
 {
    my $self = shift;
    my ( $buffref, $closed ) = @_;

    return 0 unless $$buffref =~ s/^(.*)\n//;
    my $line = $1;

    if( $line =~ m/^HELLO (.*)/ ) {
       my ( $name ) = @_;

       my $on_hello = $self->{on_hello} || $self->can( 'on_hello' );
       $on_hello->( $self, $name );
    }

    return 1;
 }

 sub send_hello
 {
    my $self = shift;
    my ( $name ) = @_;

    $self->write( "HELLO $name\n" );
 }

This small example elides such details as error handling, which a real protocol implementation would be likely to contain.

DESCRIPTION

This subclass of IO::Async:Notifier is intended to stand as a base class for implementing stream-based protocols. It provides an interface similar to IO::Async::Stream, primarily, a write method and an on_read event handler.

It contains an instance of an IO::Async::Stream object which it uses for actual communication, rather than being a subclass of it, allowing a level of independence from the actual stream being used. For example, the stream may actually be an IO::Async::SSLStream to allow the protocol to be used over SSL.

The object may be used in one of two ways; as an instance with CODE references as callbacks, or as a base class with overridden methods.

Subclassing

If a subclass is built, then it can override the following methods to handle events:

 $ret = $self->on_read( \$buffer, $handleclosed )

 $self->on_closed()

The on_read handler is invoked identically to IO::Async::Stream.

The on_closed handler is optional, but if provided, will be invoked after the stream is closed by either side (either because the close() method has been invoked on it, or on an incoming EOF).

As with IO::Async::Stream, it is required that by the time the protocol object is added to a Loop, that it either has an on_read method, or has been configured with an on_read callback handler.

PARAMETERS

The following named parameters may be passed to new or configure:

on_read => CODE

A CODE reference for when more data is available

 $ret = $on_read->( $self, \$buffer, $handleclosed )

METHODS

$self->write( $data )

Writes the given data by calling the write method on the contained transport stream.

AUTHOR

Paul Evans <leonerd@leonerd.org.uk>