Last active
August 10, 2018 19:42
-
-
Save jberger/78d7c1649d7acbab6a94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use Mojolicious::Lite; | |
use Mojo::Redis2; | |
use experimental 'signatures'; | |
helper redis => sub { state $r = Mojo::Redis2->new }; | |
get '/' => 'chat'; | |
websocket '/socket' => sub ($c, $r=$c->redis) { | |
$r->subscribe( 'chat' ); | |
my $cb = $r->on( message => sub ($r, $msg, $chan) { $c->send($msg) } ); | |
$c->on( finish => sub { $r->unsubscribe( message => $cb ) } ); | |
$c->on( message => sub ($c, $msg) { $r->publish(chat => $msg) } ); | |
$c->inactivity_timeout(3600); | |
}; | |
app->start; | |
__DATA__ | |
@@ chat.html.ep | |
<!DOCTYPE html> | |
<html> | |
<head><title>Mojo/Redis Chat Example</title></head> | |
<body> | |
<form onsubmit="sendChat(this.children[0]); return false"><input></form> | |
<div id="log"></div> | |
%= javascript begin | |
var log = document.getElementById('log'); | |
var ws = new WebSocket('<%= url_for('socket')->to_abs %>'); | |
ws.onmessage = function (e) { log.innerHTML = '<p>'+e.data+'</p>' + log.innerHTML }; | |
function sendChat(input) { ws.send(input.value); input.value = '' } | |
% end | |
</body> | |
</html> |
thanks yunikim! that works great!
document.getElementById('log').innerHTML += '<p>' + e.data + '</p>';
Hey, I'm new to Mojolicious.
is $c->redis a new Mojo::Redis2 instance per transacion ?
I'm just confused because I am trying to make a chat application with different rooms i.e
websocket '/room(:room)'
$r->subscribe( $self->param('room') )
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
getting rid of jquery without adding lines if possible
Would it work? (didn't test)