The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

WebSocket::Server - WebSocket Server

SYNOPSIS

    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 ) = @_;
            $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 );
                },
                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 );

VERSION

    v0.1.0

DESCRIPTION

This is a server class for the WebSocket protocol.

CONSTRUCTOR

new

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.

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

on_shutdown

A code reference that will be triggered upon termination of the connection.

on_tick

A code reference that will be triggered for every tick.

port

The port number on which to connect.

silence_max
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)

See also "version" to change this afterward.

watch_readable
watch_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

METHODS

compression_threshold

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.

connections

Returns the client connections currently active.

In 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" );
    });

In other context, this returns a regular array:

    for( $server->connections )
    {
        print( "Connection from ip '", $_->ip, "' on port '", $_->port, "'\n" );
    }

disconnect

Provided with the client socket filehandle and this will close the connection for that client.

extensions

Set or get the extension enabled for this server. For example permessage-deflate to enable message compression.

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.

ip

Set or get the ip address to which the server is connected to.

is_ssl

Returns true if the server is using a ssl connection, false otherwise.

This value is set automatically upon calling "start".

listen

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.

on

Provided with an array or array reference of event name and core reference pairs and this will set those event handlers.

It returns the current object.

on_connect

Set or get the code reference for the event handler that is triggered when there is a new client connection.

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" );
    });

on_shutdown

Set or get the code reference for the event handler that is triggered when the server is shutting down and before calling "disconnect" on every connected client.

on_tick

Set or get the code reference for the event handler that is triggered for every tick, if enabled.

The handler is passed the server object.

port

Returns the port to which this server is listening to.

shutdown

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.

silence_checkinterval

silence_max

socket

This is an alias for "listen". It returns the server socket object.

start

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.

subprotocol

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

tick_period

Set or get the tick interval period.

unwatch_readable

unwatch_writable

version

The version supported. Defaults to draft-ietf-hybi-17 which means version 13 (the latest as of 2021-09-24)

See rfc6455 section 4.4 for more information

Returns an array of WebSocket::Version objects, each stringifies to its numeric value.

versions

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.

watch_readable

watch_writable

watched_readable

watched_writable

CREDITS

Graham Ollis for AnyEvent::WebSocket::Client, Eric Wastl for Net::WebSocket::Server, Vyacheslav Tikhanovsky aka VTI for Protocol::WebSocket

AUTHOR

Jacques Deguest <jack@deguest.jp>

SEE ALSO

WebSocket::Client

COPYRIGHT & LICENSE

Copyright(c) 2021 DEGUEST Pte. Ltd. DEGUEST Pte. Ltd.

You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.