Skip to content

Instantly share code, notes, and snippets.

@mpapec
Created May 7, 2016 16:10
Show Gist options
  • Save mpapec/42d147971abc566435c0b149867ac37d to your computer and use it in GitHub Desktop.
Save mpapec/42d147971abc566435c0b149867ac37d to your computer and use it in GitHub Desktop.
use 5.20.0;
use Mojo::UserAgent;
use Mojo::IOLoop;
sub ws_connect {
state $ua;
my $go = sub {
say "Connecting..";
$ua = Mojo::UserAgent->new;
$ua->websocket('ws://127.0.0.1:3000/echo' => \&onConnect);
};
return $go->() if !$ua;
say "I'll try in a sec..";
Mojo::IOLoop->timer(2 => $go);
}
sub onConnect {
my ($ua, $tx) = @_;
if (!$tx->is_websocket) {
say 'WebSocket handshake failed!';
return ws_connect();
}
say "Connected!";
$tx->on(finish => sub {
my ($tx, $code, $reason) = @_;
say "WebSocket closed with status $code";
return ws_connect();
});
$tx->on(message => sub {
my ($tx, $msg) = @_;
say "WebSocket message: $msg";
# $tx->finish;
});
$tx->send('Hi!');
}
ws_connect();
Mojo::IOLoop->start; # unless Mojo::IOLoop->is_running;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment