my $ua = Mojo::UserAgent->new; my $conn = $ua->websocket("ws://localhost:8080/" => sub { my ($ua, $tx) = @_; say "WebSocket handshake failed!" and return unless $tx->is_websocket; my $id = Mojo::IOLoop->recurring(5 => sub { my @command = qw/ RUN STOP /; my $command = $command[rand @command]; say "Client > $command"; $tx->send($command); }); $tx->on(finish => sub { my ($tx, $code, $reason) = @_; say "WebSocket closed with status $code."; Mojo::IOLoop->remove($id); Mojo::IOLoop->stop_gracefully; }); $tx->on(text => sub { my ($tx, $bytes) = @_; say "Server > ", $bytes; }); }); Mojo::IOLoop->start unless Mojo::IOLoop->is_running;