DeadEater has asked for the wisdom of the Perl Monks concerning the following question:

I would like to push data to connected browsers from anywhere I like. The following code is copied from the Mojolicious tutorials (more or less).

sub websockets_handler { my $self = shift; # Opened $self->app->log->debug('WebSocket opened.'); # Increase inactivity timeout for connection a bit Mojo::IOLoop->stream($self->tx->connection)->timeout(300); # Incoming message $self->on(message => sub { my ($self, $msg) = @_; $self->send({text => $msg}); }); # Closed $self->on(finish => sub { my ($self, $code, $reason) = @_; $self->app->log->debug("WebSocket closed with status $code."); }); }

What I'd ideally like to do is insert something like this inside the websockets handler...

my $cb = $self->stash('logchanvar')->on(message => sub { my ($log, $level, @lines) = @_; $self->send({ text => $lines[0] }); ...

The $self->stash('logchanvar') is a log object. When I write to it, it emits a message event. You assign a callback to the event, then you send data to connected browsers through the websockets channel from inside the callback.

So I can just write to the log object from anywhere, then the message would get sent to the browsers. The above code doesn't work. The error message says that $self is not a websockets object. The weird thing is that if I called the $self->send... from inside an AnyEvent::Util::runcmd callback, it works. I'm new to the site. I've been programming Perl as a hobby for some years. This is just for a personal project. Nothing critical. Any help is greatly appreciated and thanks in advance.

Replies are listed 'Best First'.
Re: How do I push randomly push data to browsers using Mojolicious websockets?
by Anonymous Monk on Sep 27, 2013 at 22:18 UTC

    The above code doesn't work. The error message says that $self is not a websockets object.

    No way, that code won't run at all :)