Dancer2-Plugin-WebSocket
view release on metacpan or search on metacpan
lib/Dancer2/Plugin/WebSocket.pm view on Meta::CPAN
}
F<config.yml>:
plugins:
WebSocket:
# default values
serializer: 0
login: 0
mount_path: /ws
F<MyApp.pm>:
package MyApp;
use Dancer2;
use Dancer2::Plugin::WebSocket;
websocket_on_message sub {
my( $conn, $message ) = @_;
$conn->send( $message . ' world!' );
};
get '/' => sub {
my $ws_url = websocket_url;
return <<"END";
<html>
<head><script>
var urlMySocket = "$ws_url";
var mySocket = new WebSocket(urlMySocket);
mySocket.onmessage = function (evt) {
console.log( "Got message " + evt.data );
};
mySocket.onopen = function(evt) {
console.log("opening");
setTimeout( function() {
mySocket.send('hello'); }, 2000 );
};
</script></head>
<body><h1>WebSocket client</h1></body>
</html>
END
};
get '/say_hi' => sub {
$_->send([ "Hello!" ]) for websocket_connections;
};
true;
=head1 DESCRIPTION
C<Dancer2::Plugin::WebSocket> provides an interface to L<Plack::App::WebSocket>
and allows to interact with the webSocket connections within the Dancer app.
L<Plack::App::WebSocket>, and thus this plugin, requires a plack server that
supports the psgi I<streaming>, I<nonblocking> and I<io>. L<Twiggy>
is the most popular server fitting the bill.
=head1 CONFIGURATION
=over
=item serializer
If serializer is set to a C<true> value, messages will be assumed to be JSON
objects and will be automatically encoded/decoded using a L<JSON::MaybeXS>
serializer. If the value of C<serializer> is a hash, it'll be passed as
arguments to the L<JSON::MaybeXS> constructor.
plugins:
WebSocket:
serializer:
utf8: 1
allow_nonref: 1
By the way, if you want the connection to automatically serialize data
structures to JSON on the client side, you can do something like
var mySocket = new WebSocket(urlMySocket);
mySocket.sendJSON = function(message) {
return this.send(JSON.stringify(message))
};
// then later...
mySocket.sendJSON({ whoa: "auto-serialization ftw!" });
=item mount_path
Path for the websocket mountpoint. Defaults to C</ws>.
=back
=head1 PLUGIN KEYWORDS
In the various callbacks, the connection object C<$conn>
is a L<Plack::App::WebSocket::Connection> object
augmented with the L<Dancer2::Plugin::WebSocket::Connection> role.
=head2 websocket_on_open sub { ... }
websocket_on_open sub {
my( $conn, $env ) = @_;
...;
};
Code invoked when a new socket is opened. Gets the new
connection
object and the Plack
C<$env> hash as arguments.
=head2 websocket_on_login sub { ... }
websocket_on_login sub {
my( $conn, $env ) = @_;
...;
};
( run in 0.705 second using v1.01-cache-2.11-cpan-d7f47b0818f )