NAME
Net::WebSocket::Server - A straightforward Perl WebSocket server with minimal dependencies.
SYNOPSIS
Simple echo server for utf8
messages.
use Net::WebSocket::Server;
Net::WebSocket::Server->new(
listen => 8080,
on_connect => sub {
my ($serv, $conn) = @_;
$conn->on(
utf8 => sub {
my ($conn, $msg) = @_;
$conn->send_utf8($msg);
},
);
},
)->start;
Server that sends the current time to all clients every second.
use Net::WebSocket::Server;
my $ws = Net::WebSocket::Server->new(
listen => 8080,
tick_period => 1,
on_tick => sub {
my ($serv) = @_;
$_->send_utf8(time) for $serv->connections;
},
)->start;
Broadcast-echo server for utf8
and binary
messages with origin testing.
use Net::WebSocket::Server;
my $origin = 'http://example.com';
Net::WebSocket::Server->new(
listen => 8080,
on_connect => sub {
my ($serv, $conn) = @_;
$conn->on(
handshake => sub {
my ($conn, $handshake) = @_;
$conn->disconnect() unless $handshake->req->origin eq $origin;
},
utf8 => sub {
my ($conn, $msg) = @_;
$_->send_utf8($msg) for $conn->server->connections;
},
binary => sub {
my ($conn, $msg) = @_;
$_->send_binary($msg) for $conn->server->connections;
},
);
},
)->start;
See "listen" for an example of setting up an SSL (wss://...
) server.
DESCRIPTION
This module implements the details of a WebSocket server and invokes the provided callbacks whenever something interesting happens. Individual connections to the server are represented as Net::WebSocket::Server::Connection objects.
CONSTRUCTION
Net::WebSocket::Server->new(%opts)
-
Net::WebSocket::Server->new( listen => 8080, on_connect => sub { ... }, )
Creates a new
Net::WebSocket::Server
object with the given configuration. Takes the following parameters:listen
-
If not a reference, the TCP port on which to listen. If a reference, a preconfigured IO::Socket::INET TCP server to use. Default
80
.To create an SSL WebSocket server (such that you can connect to it via a
wss://...
URL), pass an object which acts like IO::Socket::INET and speaks SSL, such as IO::Socket::SSL. To avoid blocking during the SSL handshake, passSSL_startHandshake => 0
to the IO::Socket::SSL constructor and the handshake will be handled automatically as part of the normal server loop. For example:my $ssl_server = IO::Socket::SSL->new( Listen => 5, LocalPort => 8080, Proto => 'tcp', SSL_startHandshake => 0, SSL_cert_file => '/path/to/server.crt', SSL_key_file => '/path/to/server.key', ) or die "failed to listen: $!"; Net::WebSocket::Server->new( listen => $ssl_server, on_connect => sub { ... }, )->start;
silence_max
-
The maximum amount of time in seconds to allow silence on each connection's socket. Every
silence_max/2
seconds, each connection is checked for whether data was received since the last check; if not, a WebSocket ping message is sent. Set to0
to disable. Default20
. tick_period
-
The amount of time in seconds between
tick
events. Set to0
to disable. Default0
. on_
$event
-
The callback to invoke when the given
$event
occurs, such ason_connect
. See "EVENTS". watch_readable
watch_writable
-
Each of these takes an arrayref of
$filehandle => $callback
pairs to be passed to the corresponding method. Default[]
. See watch_readable() and watch_writable(). For example:Net::WebSocket::Server->new( # ...other relevant arguments... watch_readable => [ \*STDIN => \&on_stdin, ], watch_writable => [ $log1_fh => sub { ... }, $log2_fh => sub { ... }, ], )->start;
METHODS
on(%events)
-
$server->on( connect => sub { ... }, );
Takes a list of
$event => $callback
pairs;$event
names should not include anon_
prefix. Typically, events are configured once via the constructor rather than later via this method. See "EVENTS". start()
-
Starts the WebSocket server; registered callbacks will be invoked as interesting things happen. Does not return until shutdown() is called.
connections()
-
Returns a list of the current Net::WebSocket::Server::Connection objects.
disconnect($socket)
-
Immediately disconnects the given
$socket
without calling the corresponding connection's callback or cleaning up the socket. For that, see "disconnect" in Net::WebSocket::Server::Connection, which ultimately calls this function anyway. shutdown()
-
Closes the listening socket and cleanly disconnects all clients, causing the start() method to return.
watch_readable(@pairs)
-
$server->watch_readable( \*STDIN => \&on_stdin, );
Takes a list of
$filehandle => $callback
pairs. The given filehandles will be monitored for readability; when readable, the given callback will be invoked. Arguments passed to the callback are the server itself and the filehandle which became readable. watch_writable(@pairs)
-
$server->watch_writable( $log1_fh => sub { ... }, $log2_fh => sub { ... }, );
Takes a list of
$filehandle => $callback
pairs. The given filehandles will be monitored for writability; when writable, the given callback will be invoked. Arguments passed to the callback are the server itself and the filehandle which became writable. watched_readable([$filehandle])
watched_writable([$filehandle])
-
These methods return a list of
$filehandle => $callback
pairs that are curently being watched for readability / writability. If a filehandle is given, its callback is returned, orundef
if it isn't being watched. unwatch_readable(@filehandles)
unwatch_writable(@filehandles)
-
These methods cause the given filehandles to no longer be watched for readability / writability.
EVENTS
Attach a callback for an event by either passing on_$event
parameters to the constructor or by passing $event
parameters to the on() method.
connect($server, $connection)
-
Invoked when a new connection is made. Use this event to configure the newly-constructed Net::WebSocket::Server::Connection object. Arguments passed to the callback are the server accepting the connection and the new connection object itself.
tick($server)
-
Invoked every tick_period seconds, or never if tick_period is
0
. Useful to perform actions that aren't in response to a message from a client. Arguments passed to the callback are only the server itself. shutdown($server)
-
Invoked immediately before the server shuts down due to the shutdown() method being invoked. Any client connections will still be available until the event handler returns. Arguments passed to the callback are only the server that is being shut down.
CAVEATS
When loaded (via use
, at BEGIN
-time), this module installs a SIGPIPE
handler of 'IGNORE'
. Write failures are handled situationally rather than in a global SIGPIPE
handler, but this still must be done to prevent the signal from killing the server process. If you require your own SIGPIPE
handler, assign to $SIG{PIPE}
after this module is loaded.
AUTHOR
Eric Wastl, <topaz at cpan.org>
BUGS
Please report any bugs or feature requests to bug-net-websocket-server at rt.cpan.org
, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-WebSocket-Server. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Net::WebSocket::Server
You can also look for information at:
RT: CPAN's request tracker (report bugs here)
http://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-WebSocket-Server
AnnoCPAN: Annotated CPAN documentation
CPAN Ratings
Search CPAN
LICENSE AND COPYRIGHT
Copyright 2013 Eric Wastl.
This program is free software; you can redistribute it and/or modify it under the terms of the the Artistic License (2.0). You may obtain a copy of the full license at:
http://www.perlfoundation.org/artistic_license_2_0
Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license.
If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license.
This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder.
This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed.
Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.