[Catalyst] Bug in old Advent example of async/websockets code?

Toby Corkindale toby at dryft.net
Mon Feb 23 01:58:00 GMT 2015


It's worth noting that when I started stashing the $hd variable into
somewhere, I started getting a connection holding open.
However, attempts to CLOSE the websocket now seemed to hang on the
browser side, and were unreported on the server side.

Code follows:
has 'clients' => (
  is => 'rw',
  default => sub { +{} },
);

sub ws : Path('/ws') {
  my ($self, $c) = @_;
  $c->stash->{is_websocket} = 1;
  my $io = $c->req->io_fh;
  my $hs = Protocol::WebSocket::Handshake::Server->new_from_psgi($c->req->env);
  $hs->parse($io);
  my $hd = AnyEvent::Handle->new(fh => $io);
  $self->clients->{$hd} = 1;
  $hd->push_write($hs->to_string);
  $hd->push_write($hs->build_frame(buffer => "Echo Initiated")->to_bytes);
  my $error_cb = sub {
    my ($handle, $fatal, $message) = @_;
    if (defined $message) {
      warn "ws error: $message\n";
    }
    delete $self->clients->{$handle};
    return;
  };
  $hd->on_eof($error_cb);
  $hd->on_error($error_cb);
  $hd->on_read(sub {
  (my $frame = $hs->build_frame)->append($_[0]->rbuf);
  while (my $msg = $frame->next) {
    warn "ws: frame contained: $msg\n";
    $hd->push_write($hs->build_frame(buffer => "Hello $msg")->to_bytes);
    }
  });
}


On 23 February 2015 at 12:08, Toby Corkindale <toby at dryft.net> wrote:
> Hi,
> I've been trying to replicate the use of WebSockets in Catalyst, by
> following the example from the Advent calendar a year and a bit ago.
> ie.
> https://github.com/perl-catalyst/2013-Advent-Staging/blob/master/Websocket-Echo/lib/MyApp/Controller/Root.pm
>
> In my experience, it isn't actually working properly -- I get the
> "Echo Initiated" message, but then an instant disconnect.
>
> Looking at the code, I'm highly suspicious of the $hd variable -- it
> doesn't get stored anywhere, and according to the AnyEvent docs, I
> think that means it will get DESTROYed once it goes out of scope. ie.
> Immediately.
>
> That fits the behaviour I'm seeing, although I think I've had it work
> for me randomly at times as well, so...  I don't know.
>
> I wondered if anyone here has thoughts on the matter?
>
> Cheers,
> Toby



-- 
Turning and turning in the widening gyre
The falcon cannot hear the falconer
Things fall apart; the center cannot hold
Mere anarchy is loosed upon the world



More information about the Catalyst mailing list