After I run client against websocket echo server, it disconnects after about half a minute with WebSocket closed with status 1006
message.
Please suggest how to avoid such behavior (browser clients does not seem to be affected)
use 5.20.0;
use Mojo::UserAgent;
use Mojo::IOLoop;
sub ws_connect {
state $ua;
say "Connecting..";
$ua = Mojo::UserAgent->new;
$ua->websocket('ws://127.0.0.1:3000/echo' => \&onConnect);
}
sub onConnect {
my ($ua, $tx) = @_;
if (!$tx->is_websocket) {
say 'WebSocket handshake failed!';
}
say "Connected!";
$tx->on(finish => sub {
my ($tx, $code) = @_;
say "WebSocket closed with status $code";
});
}
ws_connect();
Mojo::IOLoop->start;
echo server
use Mojolicious::Lite;
use Mojo::EventEmitter;
helper events => sub { state $events = Mojo::EventEmitter->new };
# get '/' => 'chat';
websocket '/echo' => sub {
my $c = shift;
$c->inactivity_timeout(3600);
# Forward messages from the browser
$c->on(message => sub { shift->events->emit(mojochat => shift) });
# Forward messages to the browser
my $cb = $c->events->on(mojochat => sub { $c->send(pop) });
$c->on(finish => sub { shift->events->unsubscribe(mojochat => $cb) });
};
app->start;