++ed by:
2 non-PAUSE users
Author image Naveed Massjouni
and 1 contributors


Dancer::Plugin::WebSocket - A Dancer plugin for easily creating WebSocket apps


version 0.0100


    # ./bin/app.pl
    use Dancer;
    use Dancer::Plugin::WebSocket;

    get '/' => sub {q[
        var ws_path = "ws://localhost:5000/_hippie/ws";
        var socket = new WebSocket(ws_path);
        socket.onopen = function() {
            document.getElementById('conn-status').innerHTML = 'Connected';
        socket.onmessage = function(e) {
            var data = JSON.parse(e.data);
            if (data.msg)
                alert (data.msg);
        function send_msg(message) {
            socket.send(JSON.stringify({ msg: message }));
        Connection Status: <span id="conn-status"> Disconnected </span>
        <input value="Send Message" type=button onclick="send_msg('hello')" />


    # Run app with Twiggy
    twiggy --listen :5000 bin/app.pl

    # Now you can visit http://localhost:5000 with a browser that supports
    # WebSockets, such as Chrome.


This goal of this plugin is to make it as easy as possible to create WebSocket enabled apps with Dancer. It is built on top of Web::Hippie, but it abstracts that out as much as possible. You should be aware that it registers 2 routes that Web::Hippie needs: get('/new_listener') and get('/message'). Be careful to not define those routes in your app.

This plugin currently requires that you run your app via Twiggy. For example:

    twiggy --listen :5000 bin/app.pl


These methods allow you to interact with WebSockets from the server side. If you are only going to interact with WebSockets from javascript, as shown in the "SYNOPSIS", then these are not necessary.

ws_on_message (\&handler)

Registers a handler that gets triggered when a new message arrives. The handler gets passed 1 argument, a data structure containing the message. Note that if you register a handler in this way, the onmessage callback of the WebSocket object in your javascript will not get triggered.

    ws_on_message sub {
        my $data = shift;
        debug $data->{msg};

ws_on_new_listener (\&handler)

Registers a handler that gets triggered when a new listener is created. The handler gets passed no arguments.

    ws_on_new_listener sub {
        # do something when a new listener is created

ws_send ($message)

Allows you to send a WebSocket message from within a Dancer route.

    any '/send_msg' => sub {
        my $msg = params->{msg};
        ws_send $msg;

    # Now you can send a message to your application via curl:
    curl http://localhost:5000/send_msg?msg=hello


  • Naveed Massjouni <naveedm9@gmail.com>

  • Franck Cuny <franck@lumberjaph.net>


This software is copyright (c) 2010 by Naveed Massjouni.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.