Skip to content

Instantly share code, notes, and snippets.

@ironcamel
Created December 20, 2010 09:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ironcamel/748176 to your computer and use it in GitHub Desktop.
Save ironcamel/748176 to your computer and use it in GitHub Desktop.
A simple websocket web app using the Dancer web framework http://perldancer.org
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var socket;
$(function() {
// ws_path should be of the form ws://host/_hippie/ws
var ws_path = "ws:<% request.base.opaque %>_hippie/ws";
socket = new WebSocket(ws_path);
socket.onopen = function() {
$('#connection-status').text("Connected");
};
socket.onmessage = function(e) {
var data = JSON.parse(e.data);
if (data.msg) {
var time = Date();
$('ul').prepend('<li>' + time + ': ' + data.msg + '</li>');
}
};
});
function send_msg(message) {
socket.send(JSON.stringify({ msg: message }));
}
</script>
</head>
<body>
<h1 id="title">Dancer WebSocket Demo</h1>
Connection Status:
<span id="connection-status"> Disconnected </span>
<div>
<input value="Send Message" type=button onclick="send_msg('hello')"/>
<input value="clear" type=button onclick="$('ul').empty()"/>
</div>
<span style="font-weight:bold"> Messages </span>
<ul id="list"></ul>
</body>
</html>
#!/usr/bin/env perl
use Dancer;
use AnyMQ;
use Plack::Builder;
my $bus = AnyMQ->new;
my $topic = $bus->topic('demo');
get '/' => sub { template 'index' };
# Web::Hippie routes
get '/new_listener' => sub {
request->env->{'hippie.listener'}->subscribe($topic);
};
get '/message' => sub {
my $msg = request->env->{'hippie.message'};
$topic->publish($msg);
};
builder {
mount '/' => dance;
mount '/_hippie' => builder {
enable '+Web::Hippie';
enable '+Web::Hippie::Pipe', bus => $bus;
dance;
};
};
@ironcamel
Copy link
Author

This is a very simple demo to show how to create WebSocket enabled applications with Dancer. To run this app, you will need to install a few modules:

cpan Dancer Plack Twiggy Web::Hippie

Then create the files ./wsdemo.pl and ./views/index.tt as shown above. Then start the web server:

plackup -s Twiggy wsdemo.pl

You can then visit http://localhost:5000 in your browser. Clicking the Send Message button should show updates on your page. Open another browser window to the same url. Clicking the Send Message button should update both pages.

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