How to send a websocket message from a post?

96 views
Skip to first unread message

Lachlan Deck

unread,
May 5, 2016, 9:57:30 PM5/5/16
to Mojolicious
Hi there,

I'm using Mojo Lite as a mock api server for an angular app. 

The api currently mostly only utilises a websocket for messages from the server to the client.

Is it possible to send a message (after x seconds) via the websocket from a `post`?

Say I have:
use Mojolicious::Lite;
...

websocket
'/ws/socket' => sub {
 
...
};

post
'/foo/bar' => {
 
my $c = shift;
 
...
  $c
->render(data => encode_json {...});
 
Mojo::IOLoop->timer(2 => sub => {
    $
c->send(json => {...})
 
});
};

The message I get is `Can't call method "is_websocket" on an undefined value at /Users/ldeck/perl5/lib/perl5/Mojolicious/Controller.pm line 252.'

Is there a way to do this?

Thanks!

Matija Papec

unread,
May 6, 2016, 5:12:07 AM5/6/16
to Mojolicious
First you have to store websocket my $ws = $c->tx handle in your '/ws/socket' path, and later use this same handle to $ws->send(...)

(this applies only when server runs in single thread mode)

Lachlan Deck

unread,
May 8, 2016, 10:58:21 PM5/8/16
to mojol...@googlegroups.com
Thanks Matija,

that works.

If I do need multi-threaded support in future, where would I look?

cheers,
Lachlan

--
You received this message because you are subscribed to the Google Groups "Mojolicious" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mojolicious...@googlegroups.com.
To post to this group, send email to mojol...@googlegroups.com.
Visit this group at https://groups.google.com/group/mojolicious.
For more options, visit https://groups.google.com/d/optout.

Heiko Jansen

unread,
May 10, 2016, 4:25:54 AM5/10/16
to Mojolicious

Am Montag, 9. Mai 2016 04:58:21 UTC+2 schrieb Lachlan Deck:
 
If I do need multi-threaded support in future, where would I look?

Be aware that there´s usually no "multi-threading" in the context of Mojolicious, but asynchronous processing in multiple processes.
The solution given should work with, e.g., Morbo, where a single process handles all connections. 
IMHO, it won´t work in a production environment with Hypnotoad, because there you have a bunch of server processes and there´s no guarantee that the POST request will be handled by the same server process which controls the open websocket connection.
From the incoming POST request you could transfer some data to an external service and in every server process you could start a loop looking for new data there for those websocket connections managed by the respective hypnotoad process (maybe use https://metacpan.org/pod/Mojo::Redis2#Pub-sub here).

- heiko

Lachlan Deck

unread,
May 10, 2016, 6:08:55 AM5/10/16
to mojol...@googlegroups.com
Thanks Heiko.
The asynchronous handling of morbo is all I need at this point.

cheers,
Lachlan

Reply all
Reply to author
Forward
0 new messages