Skip to content

Instantly share code, notes, and snippets.

@kraih
Created August 26, 2011 07:33
Show Gist options
  • Save kraih/1172914 to your computer and use it in GitHub Desktop.
Save kraih/1172914 to your computer and use it in GitHub Desktop.
#!/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>
@clee
Copy link

clee commented Aug 26, 2013

This is actually really cool. I had no idea mojolicious made it this easy to serve EventSource.

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