Skip to content

Instantly share code, notes, and snippets.

@fayland
Created October 27, 2016 05:31
Show Gist options
  • Save fayland/e5ac4be8df2026063dc120854b2a0491 to your computer and use it in GitHub Desktop.
Save fayland/e5ac4be8df2026063dc120854b2a0491 to your computer and use it in GitHub Desktop.
#!/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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment