Using Protocol::WebSocket with Plack

I recently added PSGI support to Protocol::Websocket. And below is an example of WebSocket echo server using Plack, AnyEvent and Twiggy.

#!/usr/bin/env perl

use strict;
use warnings;

use AnyEvent::Handle;
use Protocol::WebSocket::Handshake::Server;
use Protocol::WebSocket::Frame;

my $psgi_app = sub {
    my $env = shift;

    my $fh = $env->{''} or return [500, [], []];

    my $hs = Protocol::WebSocket::Handshake::Server->new_from_psgi($env);
    $hs->parse($fh) or return [400, [], [$hs->error]];

    return sub {
        my $respond = shift;

        my $h = AnyEvent::Handle->new(fh => $fh);
        my $frame = Protocol::WebSocket::Frame->new;


            sub {

                while (my $message = $frame->next) {
                    $message = Protocol::WebSocket::Frame->new($message)->to_string;


I hope the code is pretty much straightforward. With the help of Protocol::WebSocket we get 75 and 76 support, easy frame parsing and nice protocol abstraction.

You try it just by running

$ twiggy app.psgi


blog comments powered by Disqus