Last active
April 5, 2021 16:12
-
-
Save raunakkathuria/633f46222f7d3a40c2ecd0234e1cb3e0 to your computer and use it in GitHub Desktop.
Perl IO::Async socket connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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