Skip to content

Commit

Permalink
make feed example auto-reconnect forever
Browse files Browse the repository at this point in the history
  • Loading branch information
preaction committed Dec 24, 2016
1 parent 63bff23 commit b03c76f
Showing 1 changed file with 22 additions and 16 deletions.
38 changes: 22 additions & 16 deletions eg/feed.pl
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,28 @@ =head1 SEE ALSO
use Mojo::UserAgent;

my $topic = $ARGV[0] || 'http://api.cpantesters.org/v1/upload';
my $ua = Mojo::UserAgent->new(
inactivity_timeout => 60000,
);
$ua->websocket( $topic => sub( $ua, $tx ) {
say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
say sprintf "[%s] Connected", scalar localtime;
$tx->on( json => sub( $tx, $upload ) {
say sprintf qq{[%s] Got upload: %s (%s) by %s},
scalar localtime, $upload->@{qw( dist version author )};
} );
$tx->on( finish => sub( $tx, $code ) {
say sprintf "[%s] Connection closed: %s",
scalar localtime, $code;
Mojo::IOLoop->stop;

sub open_socket {
state $ua = Mojo::UserAgent->new(
inactivity_timeout => 60000,
);
$ua->websocket( $topic => sub( $ua, $tx ) {
say 'WebSocket handshake failed: ' . $tx->error->{message} and return unless $tx->is_websocket;
say sprintf "[%s] Connected", scalar localtime;
$tx->on( json => sub( $tx, $upload ) {
say sprintf qq{[%s] Got upload: %s (%s) by %s},
scalar localtime, $upload->@{qw( dist version author )};
} );
$tx->on( finish => sub( $tx, $code ) {
say sprintf "[%s] Connection closed: %s",
scalar localtime, $code;
Mojo::IOLoop->stop;
} );
} );
} );
}

Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
while ( 1 ) {
open_socket() && Mojo::IOLoop->start;
sleep 1;
}

0 comments on commit b03c76f

Please sign in to comment.