Created
August 26, 2011 07:33
-
-
Save kraih/1172914 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
get '/' => 'index'; | |
get '/events' => sub { | |
my $self = shift; | |
# Emit "dice" event every second | |
$self->res->headers->content_type('text/event-stream'); | |
my $id = Mojo::IOLoop->recurring(1 => sub { | |
my $pips = int(rand 6) + 1; | |
$self->write("event:dice\ndata: $pips\n\n"); | |
}); | |
$self->on(finish => sub { Mojo::IOLoop->remove($id) }); | |
}; | |
app->start; | |
__DATA__ | |
@@ index.html.ep | |
<!doctype html><html> | |
<head><title>Roll The Dice</title></head> | |
<body> | |
<script> | |
var events = new EventSource('<%= url_for 'events' %>'); | |
// Subscribe to "dice" event | |
events.addEventListener('dice', function(event) { | |
document.body.innerHTML += event.data + '<br/>'; | |
}, false); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is actually really cool. I had no idea mojolicious made it this easy to serve EventSource.