Skip to content

Instantly share code, notes, and snippets.

@jberger
Created July 4, 2013 18:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jberger/5929620 to your computer and use it in GitHub Desktop.
Save jberger/5929620 to your computer and use it in GitHub Desktop.
Minimal Mojolicious websocket example
#!/usr/bin/env perl
use Mojolicious::Lite;
any '/' => 'index';
websocket '/time' => sub {
my $c = shift;
my $t = Mojo::IOLoop->recurring( 1 => sub {
$c->send( time );
});
$c->on( finish => sub { Mojo::IOLoop->remove($t) } );
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<div id="message"></div>
%= javascript begin
var ws = new WebSocket('<%= url_for('time')->to_abs %>');
ws.onmessage = function(e){
$('#message').append('<p>' + e.data + '</p>');
}
% end
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment