Created
December 20, 2010 09:01
-
-
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
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
<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> |
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 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; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
Then create the files ./wsdemo.pl and ./views/index.tt as shown above. Then start the web server:
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.