NAME

IO::AsyncX::Sendfile - adds support for Sys::Sendfile to IO::Async::Stream

VERSION

version 0.003

SYNOPSIS

$stream->sendfile(
 file => 'somefile',
)->on_done(sub {
 $stream->close;
});

DESCRIPTION

NOTE: This is currently a proof-of-concept, the actual API may vary in later versions. Eventually this functionality will be incorporated into the generic async filehandling API, so this module is provided as a workaround in the interim.

Provides a "sendfile" method on IO::Async::Stream.

METHODS

Note that these methods are injected directly into IO::Async::Stream.

sendfile

Write the contents of the file directly to the socket without reading it into memory first (using the kernel's sendfile call if available).

Called with the following named parameters:

  • file - if defined, this will be used as the filename to open

  • fh - if defined, we'll use this as the filehandle

  • length - if defined, send this much data from the file (default is 'everything from current position to end')

Returns a Future which will be resolved with the number of bytes written when successful.

Example usage:

my $listener = $loop->listen(
    addr => {
        family => 'unix',
        socktype => 'stream',
        path => 'sendfile.sock',
    },
    on_stream => sub {
        my $stream = shift;
        $stream->configure(
            # IO::Async::Stream needs an on_read callback, so we provide a placeholder
            on_read => sub { 0 },
        );
        # Single file with completion callback:
        $stream->sendfile(
            file => 'test.dat',
        )->on_done(sub {
            warn "File send complete: @_\n";
            $stream->close;
        });
        # Send multiple files in succession: (start the next after the first finishes)
        $stream->sendfile(file => 'first.dat');
        $stream->sendfile(file => 'second.dat');
        $stream->write('EOF', on_flush => sub { shift->close });
        $loop->add($stream);
    }
);

If the sendfile call fails, the returned Future will fail with the string exception from $! as the failure reason, with sendfile => numeric $!, remaining bytes as the remaining details:

==> ->fail("Some generic I/O error", "sendfile", EIO, 60000)

SEE ALSO

Sys::Sendfile

AUTHOR

Tom Molesworth <cpan@perlsite.co.uk>

LICENSE

Copyright Tom Molesworth 2013-2025. Licensed under the same terms as Perl itself.