为什么 websocket 连接中断
Why websocket connections breaks
在我 运行 客户端针对 websocket 回显服务器后,它在大约半分钟后断开连接并显示 WebSocket closed with status 1006
消息。
请建议如何避免这种行为(浏览器客户端似乎不受影响)
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;
回显服务器
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;
如果客户端和服务器之间没有数据,则可能您已达到不活动超时。
你试过增加inactivity_timeout
吗? (或者您可以简单地将其设置为 0
以实现无限制的不活动)
在我 运行 客户端针对 websocket 回显服务器后,它在大约半分钟后断开连接并显示 WebSocket closed with status 1006
消息。
请建议如何避免这种行为(浏览器客户端似乎不受影响)
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;
回显服务器
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;
如果客户端和服务器之间没有数据,则可能您已达到不活动超时。
你试过增加inactivity_timeout
吗? (或者您可以简单地将其设置为 0
以实现无限制的不活动)