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->close(); } }); $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.
on_establish
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.
on
$event is a string and $handler is a subroutine reference.
$event
$handler
Possible value for $event is:
"message"
$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.
$connection
$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.
$unregister
"finish"
"close"
$handler->($connection)
$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" ); $unregister->(); }); # could also be written as $connection->on( message => sub { my( $conn, $message, $unregister ) = @_; $conn->send( "This will only be sent once" ); $unregister->(); });
Send a message via $connection.
$message should be a UTF-8 encoded string.
Close the WebSocket $connection.
Toshio Ito, <toshioito at cpan.org>
<toshioito at cpan.org>
To install Plack::App::WebSocket, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Plack::App::WebSocket
CPAN shell
perl -MCPAN -e shell install Plack::App::WebSocket
For more information on module installation, please visit the detailed CPAN module installation guide.