Advertisement
Guest User

Untitled

a guest
Oct 27th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. #!/usr/bin/env perl
  2.  
  3. use Mojolicious::Lite;
  4. use Mojo::Redis2;
  5. use Scalar::Util;
  6.  
  7. helper redis => sub { shift->stash->{redis} ||= Mojo::Redis2->new(
  8. url => 'redis://127.0.0.1:6379/1'
  9. ); };
  10.  
  11. websocket '/' => sub {
  12. my $c = shift;
  13.  
  14. my $log = $c->app->log;
  15.  
  16. $log->debug('[ws] client connected');
  17. $c->inactivity_timeout(30);
  18. Scalar::Util::weaken($c);
  19.  
  20. $c->on(message => sub {
  21. my ( $c, $msg ) = @_;
  22.  
  23. $log->debug("[ws] < $msg");
  24. if ($msg =~ m/^sub:(\w+)$/) {
  25. my @channels = split(/\s*\,\s*/, $1);
  26. $c->stash->{channels} = [@channels];
  27. $c->redis->subscribe([@channels] => sub {
  28. my ( $redis, $err ) = @_;
  29. $log->error("[REDIS ERROR] subscribe error: $err") if $err;
  30. } );
  31. }
  32. });
  33.  
  34. $c->on(finish => sub {
  35. my ( $c, $code, $reason ) = @_;
  36.  
  37. $log->debug("[ws] client disconnected with status $code");
  38. # $c->redis->unsubscribe(delete $c->stash->{channels});
  39. delete $c->stash->{redis};
  40. } );
  41.  
  42. $c->redis->on(message => sub {
  43. my ( $redis, $message, $ch ) = @_;
  44.  
  45. return unless grep { $ch eq $_ } @{ $c->stash->{channels} };
  46. $log->debug("[ws][$ch] > $message");
  47. $c->send($message);
  48. } );
  49. };
  50.  
  51. app->start;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement