WebSocket::Server - WebSocket Server
use WebSocket::Server; use JSON; my $origin = 'http://localhost'; my $j = JSON->new->relaxed->convert_blessed; my $ws = WebSocket::Server->new( debug => 3, port => 8080, on_connect => sub { my( $serv, $conn ) = @_; # Set the code that will issue pong reply to ping queries from the client $conn->do_pong(sub { # WebSocket::Connection and a scalar of bytes received my( $c, $bytes ) = @_; # This is the default behaviour return( $c->pong( $bytes ) ); }); # See WebSocket::Connection for more information on the followings: $conn->on( handshake => sub { my( $conn, $handshake ) = @_; print( "Connection from ip '", $conn->ip, "' on port '", $conn->port, "'\n" ); print( "Query string: '", $handshake->request->uri->query, "'\n" ); print( "Origin is: '", $handshake->request->origin, "', ", ( $handshake->request->origin eq $origin ? '' : 'not ' ), "ok\n" ); # $conn->disconnect() unless( $handshake->request->origin eq $origin ); }, ping => \&on_ping, pong => \&on_pong, ready => sub { my $conn = shift( @_ ); my $hash = { code => 200, type => 'user', message => "Hello" }; my $json = $j->encode( $hash ); $conn->send_utf8( $json ); }, utf8 => sub { my( $conn, $msg ) = @_; # $conn->send_utf8( $msg ); print( "Received message: '$msg'\n" ); }, disconnect => sub { my( $conn, $code, $reason ) = @_; print( "Client diconnected from ip '", $conn->ip, "'\n" ); }, ); }, ) || die( WebSocket::Server->error ); $ws->start || die( $ws->error );
v0.1.1
This is a server class for the WebSocket protocol.
Instantiate a new WebSocket server object. This takes the following options:
extensions
Optional. One or more extension enabled for this server. For example permessage-deflate to enable message compression.
permessage-deflate
You can set this to either a string or a WebSocket::Extension object if you want, for example to set the extension parameters.
See rfc6455 section 9.1 for more information on extension.
Seel also "compression_threshold".
listen
Optional. A IO::Socket object, or one of its inheriting packages. This enables you to instantiate your own IO::Socket object and pass it here to be used. 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: $!"; my $server = WebSocket::Server->new( listen => $ssl_server ) || die( WebSocket::Server->error );
on_connect
A code reference that will be triggered upon connection from client.
It will be passed the the server object and the connection object (WebSocket::Connection).
See "on_connect" for more information.
on_shutdown
A code reference that will be triggered upon termination of the connection.
See "on_shutdown" for more information.
on_tick
A code reference that will be triggered for every tick.
See "on_tick" for more information.
port
The port number on which to connect.
silence_max
The maximum value for ping frequency.
tick_period
Frequency for the tick.
version
The version supported. Defaults to draft-ietf-hybi-17 which means version 13 (the latest as of 2021-09-24)
draft-ietf-hybi-17
13
See also "version" to change this afterward.
watch_readable
An array reference of filehandle and subroutine callback as code reference. Each callback will be passed the WebSocket::Server object and the socket filehandle.
The callback is called when the filehandle provided becomes readable.
watch_writable
The callback is called when the filehandle provided becomes writable.
If there are any issue with the instantiation, it will return undef and set an error WebSocket::Exception that can be retrieved with the error method inherited from Module::Generic
undef
Inherited from WebSocket
Set or get the threshold in bytes above which the ut8 or binary messages will be compressed if the client and the server support compression and it is activated as an extension.
Returns the client connections currently active.
In list context, or if the legacy is turned on, this returns a regular array:
legacy
for( $server->connections ) { print( "Connection from ip '", $_->ip, "' on port '", $_->port, "'\n" ); }
In any other context, including object context, this returns a Module::Generic::Array, such as:
$server->connections->for(sub { my $conn = shift( @_ ); print( "Connection from ip '", $conn->ip, "' on port '", $conn->port, "'\n" ); });
Provided with the client socket filehandle and this will close the connection for that client.
Set or get the extension enabled for this server. For example permessage-deflate to enable message compression.
Set or get the ip address to which the server is connected to.
Returns true if the server is using a ssl connection, false otherwise.
This value is set automatically upon calling "start".
Set or get the boolean value whether the method "connections" use the legacy pattern and returns a list of current connection objects, or if false, it returns an array object instead. This defaults to false.
Get the IO::Socket (or any of its inheriting classes such as IO::Socket::INET or IO::Socket::SSL) server socket object.
This value is set automatically upon calling "start", or it can also be provided upon server object instantiation. See "new" option parameters.
Provided with an hash or hash reference of event name and code reference pairs and this will set those event handlers.
Possible event names are: connect, shutdown, tick.
connect
shutdown
tick
See below their corresponding method for more details.
See also WebSocket::Connection for event handlers that can be set when a connection has been established.
It returns the current object.
Set or get the code reference for the event handler that is triggered when there is a new client connection, and after the connection has been established.
The handler is passed the server object and the connection object.
$server->on_connect(sub { my( $s, $conn ) = @_; print( "Connection received from ip '", $conn->ip, "'\n" ); # set handler for each event # See WebSocket::Connection for details on the arguments provided # You can also check out the example given in the symopsis $conn->on( handshake => $self->curry::onconnect, ready => $self->curry::onready, utf8 => $self->curry::onmessage, binary => $self->curry::onbinary, pong => $self->curry::onpong, disconnect => $self->curry::onclose, ); });
Any fatal error occurring in the callback are caught using try-catch with (Nice::Try), and if an error occurs, this method will raise a warning if warnings are enabled.
Set or get the code reference for the event handler that is triggered before calling "disconnect" on every connected client and before the server is shutting down.
The callback is provided this server object as its sole argument.
Set or get the code reference for the event handler that is triggered for every tick, if enabled by setting "tick_period" to a true value.
The handler is passed this server object.
Sets or gets the port on which this server is listening to.
Shuts down the server connection, calls the event handler "on_shutdown", and calls disconnect on each active client connection passing them the code 1001
It returns the current server object.
Sets or gets the interval in seconds. This is used to set the frequency of pings and also contribute to set the timeout.
This is an alias for "listen". It returns the server socket object.
Starts the server.
If a socket object has already been initiated and provided with the "new" option listen, then it will be used, otherwise, it will instantiate a new IO::Socket::INET connection. If a port option was provided in "new", it will be used, otherwise it will be auto allocated and the port assigned can then be retrieved using the "port" method.
For every client connection received, it will instantiate a new WebSocket::Connection object and call the "on_connect" event handler, passing it the server object and the connection object.
If tick_period option in "new" has been set, this will trigger the "on_tick" event handler at the tick_period interval.
Set or get an array object of WebSocket protocols. This array object will be passed to each new WebSocket::Connection object upon each connection received.
Returns a Module::Generic::Array object.
See rfc6455 for more information
Set or get the tick interval period.
This takes one or more filehandle, and removes them from being watched.
See rfc6455 section 4.4 for more information
Returns an array of WebSocket::Version objects, each stringifies to its numeric value.
Set or get the list of supported protocol versions.
It can take inteer sucha s 13, which is the latest WebSocket rfc6455 protocol version, or one or more WebSocket::Version objects.
This takes a list or an array reference of filehandle and subroutine callback as code reference. Each callback will be passed the WebSocket::Server object and the socket filehandle.
my $code = $ws->watched_readable( $fh ); my( $fh1, $code1, $fh2, $code2 ) = $ws->watched_readable; my @all = $ws->watched_readable;
If a file handle is provided as a unique argument, it returns the corresponding callback, if any.
Otherwise, if no argument is provided, it returns a list of file handle and their calback.
my $code = $ws->watched_writable( $fh ); my( $fh1, $code1, $fh2, $code2 ) = $ws->watched_writable; my @all = $ws->watched_writable;
Graham Ollis for AnyEvent::WebSocket::Client, Eric Wastl for Net::WebSocket::Server, Vyacheslav Tikhanovsky aka VTI for Protocol::WebSocket
Jacques Deguest <jack@deguest.jp>
WebSocket::Client
Copyright(c) 2021-2023 DEGUEST Pte. Ltd.
You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.
To install WebSocket, copy and paste the appropriate command in to your terminal.
cpanm
cpanm WebSocket
CPAN shell
perl -MCPAN -e shell install WebSocket
For more information on module installation, please visit the detailed CPAN module installation guide.