Mojolicious::Lite websocket doens't work

75 views
Skip to first unread message

Pavel Serikov

unread,
Oct 19, 2015, 4:53:46 PM10/19/15
to Mojolicious
Hi everyone,
I need a simple app which got POST request and send its content through websocket to all connected browser clients.

I wrote a code,

#!/usr/bin/env perl
use Mojolicious::Lite;
use feature 'say';

my $clients = {};
my $curr_msg = {};

post
'/' => sub {
 
my $self = shift;
 
my $params = $self->req->params->names;
 
for (@$params) {
    $curr_msg
->{$_} = $self->param($_);
 
};
  $self
->render(json => { status => 'post ok', data => $curr_msg});  
};

websocket
'/ws' => sub {
       
my $self = shift;
        app
->log->debug(sprintf 'Client connected: %s', $self->tx);
       
my $id = sprintf "%s", $self->tx;
        $clients
->{$id} = $self->tx;

       
if (%$curr_msg) {
         
for (keys %$clients) {
              $clients
->{$_}->send(json => $curr_msg);
           
};
           $curr_msg
= {};
       
};

        $self
->on(finish => sub {
            app
->log->debug('Client disconnected');
           
delete $clients->{$id};
       
});
   
};

app
->start;

But for some reason it doesn't work - not sending json to clients. I have no idea why and how to debug.
Does anyone see any bad things in my code?

Any suggestion is much appreciated.

sri

unread,
Oct 19, 2015, 5:21:58 PM10/19/15
to Mojolicious
There's example applications for this.


For a scalable solution you'll need a pub/sub backend like PostgreSQL or Redis.

--
sebastian

Pavel Serikov

unread,
Oct 20, 2015, 6:04:38 PM10/20/15
to Mojolicious
Dear Sebastian, thank you for your reply.
I used your example and modified mine (result) for using with Mojo::EventEmitter, now everything works fine.

Could you please also explain, what do I need to store in database (pub/sub backend like PostgreSQL or Redis) in case of scalable solution?

вторник, 20 октября 2015 г., 0:21:58 UTC+3 пользователь sri написал:

sri

unread,
Oct 20, 2015, 6:07:16 PM10/20/15
to Mojolicious
Could you please also explain, what do I need to store in database (pub/sub backend like PostgreSQL or Redis) in case of scalable solution?

Nothing, you're using PostgreSQL/Redis as a message bug, to broadcast your messages to all servers.

--
sebastian 
Reply all
Reply to author
Forward
0 new messages