Сухой27 Сухой27 - 6 months ago 30
Perl Question

Why websocket connections breaks

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;

Answer

If there is no data between client and server maybe you have reached inactivity timeout.

Have you tried to increase the inactivity_timeout? (or you can simply set it to 0 for unlimited inactivity)