Skip to content

Instantly share code, notes, and snippets.

@Prajithp
Last active July 1, 2016 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Prajithp/ac6d6ca6a59d4f7ab534ab1b1dd50c18 to your computer and use it in GitHub Desktop.
Save Prajithp/ac6d6ca6a59d4f7ab534ab1b1dd50c18 to your computer and use it in GitHub Desktop.
mojo event loop
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