Plack::App::WebSocket::Connection - WebSocket connection for Plack::App::WebSocket


    my $app = Plack::App::WebSocket->new(on_establish => sub {
        my $connection = shift;
        $connection->on(message => sub {
            my ($connection, $message) = @_;
            warn "Received: $message\n";
            if($message eq "quit") {
        $connection->on(finish => sub {
            warn "Closed\n";
            undef $connection;
        $connection->send("Message to the client");


Plack::App::WebSocket::Connection is an object representing a WebSocket connection to a client. It is created by Plack::App::WebSocket internally and given to you in on_establish callback function.


@unregister = $connection->on($event => $handler, $event2 => $handler2, ...)

Register a callback function to a particular event. You can register multiple callbacks to the same event. You can register multiple callbacks by a single call to on method.

$event is a string and $handler is a subroutine reference.

Possible value for $event is:

    $handler->($connection, $message, $unregister)

$handler is called for each message received via the $connection. Argument $connection is the Plack::App::WebSocket::Connection object, and $message is a non-decoded byte string of the received message.

$unregister is a subroutine reference. When you invoke it, it removes the handler from the $connection, so that it'll be never called again. See below for an example.

"finish" (alias: "close")

$handler is called when the $connection is closed. Argument $connection is the Plack::App::WebSocket::Connection object.

on method returns list of subroutine references that unregister the $handlers just registered.

In scalar context, it returns the first subroutine reference.

Example of unregistering:

    my $unregister;
    $unregister = $connection->on( message => sub {
        my( $conn, $message ) = @_;
        $conn->send( "This will only be sent once" );

    # could also be written as
    $connection->on( message => sub {
        my( $conn, $message, $unregister ) = @_;
        $conn->send( "This will only be sent once" );


Send a message via $connection.

$message should be a UTF-8 encoded string.


Close the WebSocket $connection.


Toshio Ito, <toshioito at>