为什么 websocket 连接中断 [英] Why websocket connections breaks

查看:107
本文介绍了为什么 websocket 连接中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我对 websocket 回显服务器运行客户端后,它在大约半分钟后断开连接,WebSocket 关闭并显示状态 1006 消息.

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;

回声服务器

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;

推荐答案

如果客户端和服务器之间没有数据,可能您已经达到不活动超时.

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

您是否尝试过增加 inactivity_timeout?(或者您可以简单地将其设置为 0 以实现无限不活动)

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

这篇关于为什么 websocket 连接中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆