Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
Perl-Sensitive Sunglasses
 
PerlMonks  

How do I push randomly push data to browsers using Mojolicious websockets?

by DeadEater (Initiate)
on Sep 27, 2013 at 21:26 UTC ( #1056079=perlquestion: print w/ replies, xml ) Need Help??
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.

Comment on How do I push randomly push data to browsers using Mojolicious websockets?
Select or Download Code
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 :)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1056079]
Approved by hdb
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (10)
As of 2014-04-17 07:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (440 votes), past polls