Skip to content

Instantly share code, notes, and snippets.

@zpmorgan
Created September 22, 2012 00:47
Show Gist options
  • Save zpmorgan/3764706 to your computer and use it in GitHub Desktop.
Save zpmorgan/3764706 to your computer and use it in GitHub Desktop.
pub/sub with mojolicious, redis, & websockets.
#!/usr/bin/env perl
use Mojolicious::Lite;
use common::sense;
use Mojo::JSON;
my $json = Mojo::JSON->new();
use Mojo::Redis;
use Protocol::Redis::XS;
get '/' => sub{
my $self = shift;
$self->render(template=>'ws_page')
};
get '/pub' => sub{
my $pubsub = Mojo::Redis->new;
$pubsub->publish(g => 'foo',sub{$pubsub});
shift->render(text=>'published')
};
# This action will render a template
websocket '/ws' => sub {
my $self = shift;
my $ws = $self->tx;
$ws->send('hello');
my $pubsub = Mojo::Redis->new;
$pubsub->protocol_redis("Protocol::Redis::XS");
$pubsub->timeout(180);
$self->stash(pubsub_redis => $pubsub);
$pubsub->subscribe('g' => sub{
my ($redis, $event) = @_;
$ws->send($event->[0]);
say @$event;
});
$self->on(message => sub {
my ($ws, $msg) = @_;
});
$self->on(finish => sub {
my $ws = shift;
say 'WebSocket closed.';
});
Mojo::IOLoop->recurring(10 => sub{
$ws->send('hello');
});
};
my $port = 7473;
app->start('daemon', '--listen' => "http://*:$port");
__DATA__
@@ws_page.html.ep
<!DOCTYPE html>
<html><head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
</head><body>
<h1>websocket.</h1>
<div id='msgs'> </div>
<script type="text/javascript">
var conn;
$(document).ready(function(){
conn = new WebSocket('ws://127.0.0.1:7473/ws');
conn.onmessage = function (event) {
$('#msgs').append('msg: '+event.data +"<br />");
};
conn.onopen = function () {
$('#msgs').append("connected.\n");
};
conn.onclose = function () {
$('#msgs').append("closed.\n");
};
});
</script>
<a href="/pub">pub</a>
</body></html>
@dpetrov
Copy link

dpetrov commented Oct 30, 2012

Mojo::Redis is suppose to be MojoX::Redis

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment