The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

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

SYNOPSIS

    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->close();
            }
        });
        $connection->on(finish => sub {
            warn "Closed\n";
            undef $connection;
        });
        $connection->send("Message to the client");
    });

DESCRIPTION

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.

OBJECT METHODS

$connection->on($event => $handler)

Register a callback function to a particular event. You can register multiple callbacks to the same event.

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

Possible value for $event is:

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

$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.

"finish" (alias: "close")
    $handler->($connection)

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

$connection->send($message)

Send a message via $connection.

$message should be a UTF-8 encoded string.

$connection->close()

Close the WebSocket $connection.

AUTHOR

Toshio Ito, <toshioito at cpan.org>