Last active
July 1, 2016 15:03
-
-
Save Prajithp/ac6d6ca6a59d4f7ab534ab1b1dd50c18 to your computer and use it in GitHub Desktop.
mojo event loop
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
sub connect { | |
my $self = shift; | |
if ( $self->connected ) { | |
$self->ioloop->remove( $self->{_connection} ); | |
} | |
my $port; | |
my $address; | |
if ( $self->host =~ m{^([^:]+)(:(\d+))?} ) { | |
$address = $1; | |
$port = $3; | |
} | |
Scalar::Util::weaken $self; | |
$self->{_connection} = $self->ioloop->client( | |
{ address => $address, | |
port => $port | |
}, | |
sub { | |
my ( $loop, $err, $stream ) = @_; | |
if ($err) { | |
$self->error($err); | |
$self->on_error->($self); | |
return; | |
} | |
$stream->on( | |
read => sub { | |
my ( $stream, $chunk ) = @_; | |
print $chunk . "\n"; | |
} | |
); | |
$stream->on( | |
close => sub { | |
my $str = shift; | |
$self->{error} ||= 'disconnected'; | |
delete $self->{_message_queue}; | |
warn 'disconnected'; | |
delete $self->{_connecting}; | |
delete $self->{_connection}; | |
} | |
); | |
$stream->on( | |
error => sub { | |
my ( $str, $error ) = @_; | |
say $error; | |
$self->ioloop->remove( $self->{_connection} ); | |
} | |
); | |
} | |
); | |
return $self; | |
} | |
sub login { | |
my $self = shift; | |
my $login_hash = { Action => 'Login', Username => $self->user, Secret => $self->secret }; | |
$self->connect unless $self->{_connection}; | |
my $login = $self->make_packet(%$login_hash); | |
if ( my $id = $self->{_connection}) { | |
$self->ioloop->stream($id)->write($login); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment