use strict; use Mojo::UserAgent; my $ua = Mojo::UserAgent->new; my $url = "ws://some.url/path"; my $globals; my $connect_ws; $connect_ws = sub { my ($ua, $tx) = @_; $tx->on(json => sub { my ($tx, $json) = @_; # populate $globals here and listen for $opcode = 7 # if ($opcode eq 7) { $tx->finish(); } }); $tx->on(finish => sub { my ($ws, $code, $reason) = @_; print "WebSocket closed with status $code. $reason\n"; $ua->websocket($url => $connect_ws); }); # if we have some globals, then we're resuming - send tokens etc if ($globals) { $tx->send({ json => $globals }) } }; $ua->websocket($url => $connect_ws); Mojo::IOLoop->start unless Mojo::IOLoop->is_running;