Created
May 7, 2016 16:10
-
-
Save mpapec/42d147971abc566435c0b149867ac37d to your computer and use it in GitHub Desktop.
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 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