Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env perl
- use Mojolicious::Lite;
- use Mojo::Redis2;
- use Scalar::Util;
- helper redis => sub { shift->stash->{redis} ||= Mojo::Redis2->new(
- url => 'redis://127.0.0.1:6379/1'
- ); };
- websocket '/' => sub {
- my $c = shift;
- my $log = $c->app->log;
- $log->debug('[ws] client connected');
- $c->inactivity_timeout(30);
- Scalar::Util::weaken($c);
- $c->on(message => sub {
- my ( $c, $msg ) = @_;
- $log->debug("[ws] < $msg");
- if ($msg =~ m/^sub:(\w+)$/) {
- my @channels = split(/\s*\,\s*/, $1);
- $c->stash->{channels} = [@channels];
- $c->redis->subscribe([@channels] => sub {
- my ( $redis, $err ) = @_;
- $log->error("[REDIS ERROR] subscribe error: $err") if $err;
- } );
- }
- });
- $c->on(finish => sub {
- my ( $c, $code, $reason ) = @_;
- $log->debug("[ws] client disconnected with status $code");
- # $c->redis->unsubscribe(delete $c->stash->{channels});
- delete $c->stash->{redis};
- } );
- $c->redis->on(message => sub {
- my ( $redis, $message, $ch ) = @_;
- return unless grep { $ch eq $_ } @{ $c->stash->{channels} };
- $log->debug("[ws][$ch] > $message");
- $c->send($message);
- } );
- };
- app->start;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement