Skip to content

Instantly share code, notes, and snippets.

@raunakkathuria
Last active April 5, 2021 16:12
Show Gist options
  • Save raunakkathuria/633f46222f7d3a40c2ecd0234e1cb3e0 to your computer and use it in GitHub Desktop.
Save raunakkathuria/633f46222f7d3a40c2ecd0234e1cb3e0 to your computer and use it in GitHub Desktop.
Perl IO::Async socket connection
use strict;
use warnings;
use IO::Async::Stream;
use IO::Async::Socket;
use IO::Async::Loop;
use Log::Any qw($log);
require Log::Any::Adapter;
Log::Any::Adapter->set(qw(Stdout), log_level => 'trace');
my $loop = IO::Async::Loop->new;
my $conn = $loop->connect(
    addr => {
       family   => "inet",
       ip     => "<HOST_TO_CONNECT>",
       port  => "<PORT>",
       socktype => 'stream',
   }
)->on_fail(sub {
    my ($socket, $family, $socktype, $protocol, $error) = @_;
    $log->debugf('Failed with %s', $error);
})->get;
$log->debug('Connected');
$loop->add(
    my $stream = IO::Async::Stream->new(
        handle => $conn,
        on_read => sub {
            my ($stream, $buffref, $eof) = @_;
            $log->debugf('Received %s', $$buffref);
            while ($$buffref =~ s/^(.*\n)//) {
                $log->debugf('Message is %s', $1);
            }
            if ($eof) {
                $log->debugf("EOF; last partial line is %s", $$buffref);
            }
            return 0;
        },
        on_read_error => sub {
            $log->errorf("Read error %s", shift);
        },
        on_write_error => sub {
            $log->errorf("Write error %s", shift);
        },
        on_closed => sub {
            $log->debugf("Stream for client has been closed");
        },
    )
);
$log->debug('Writing to stream');
$stream->write("Your message here\n")->get;
$loop->run;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment