The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

WebSocket::Client - WebSocket Client

SYNOPSIS

    use WebSocket::Client;
    use Term::Prompt;
    my $uri = "ws://localhost:8080?csrf=token";
    my $ws;
    $ws = WebSocket::Client->new( $uri,
    {
        do_pong       => sub{ $ws->pong },
        on_binary     => \&on_binary,
        on_connect    => \&on_connect,
        on_disconnect => \&on_disconnect,
        on_error      => \&on_error,
        on_handshake  => \&on_handshake,
        on_ping       => \&on_ping,
        on_pong       => \&on_pong,
        on_recv       => \&on_recv,
        on_send       => \&on_send,
        on_utf8       => \&on_message,
        origin        => 'http://localhost',
        debug         => 3,
        version       => 13,
    }) || die( WebSocket::Client->error );
    $ws->connect() || die( $ws->error );

    $SIG{INT} = $SIG{TERM} = sub
    {
        my( $sig ) = @_;
        $ws->disconnect if( $ws );
        exit( $sig eq 'TERM' ? 0 : 1 );
    };
    
    while(1)
    {
        my $msg = prompt( 'x', "> ", 'type the message to send', '' );
        next unless( $msg =~ /\S+/ );
        $ws->send_utf8( $msg ) || die( $ws->error );
    }

VERSION

    v0.1.1

DESCRIPTION

This is the WebSocket client class. It contains all the methods and api to connect to a remote WebSocket server and interact with it.

CONSTRUCTOR

new

The constructor takes an uri and the following options. If an uri is not provided as a first argument, it can be provided as a uri parameter; see below:

compression_threshold

See "compression_threshold"

A Cookie http field header value. It must be properly formatted.

do_pong

The code reference used to issue a pong. By default this is set to "pong"

extensions

Optional. One or more extension enabled for this client. 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".

max_fragments_amount
max_payload_size
on_binary

A code reference that will be triggered upon a binary message received from the server.

See "on_binary" for more details.

on_connect

A code reference that will be triggered upon successful connection to the remote WebSocket server, but before any handshake is performed.

See "on_connect" for more details.

on_disconnect

A code reference that will be triggered upon the closing of the connection with the server.

See "on_disconnect" for more details.

on_error

A code reference that will be triggered whenever an error is encountered upon parsing of the handshake.

See "on_error" for more details.

on_handshake

A code reference that will be triggered just before the handshake procedure is completed, but right after the handshake has been received from the server.

Be careful, the code reference must return true upon success, or else, it will trigger a handshake failure.

on_ping

A code reference that will be triggered when a ping is received from the WebSocket server.

See "on_ping" for more details. and Mozilla documentation on ping and pong

See also "do_pong" to set the code reference to perform a pong

on_pong

A code reference that will be triggered when a pong is received from the WebSocket server, most likely as a reply to our initial ping.

See "on_pong" for more details. and Mozilla documentation on ping and pong

on_recv

A code reference that will be triggered whenever some text or binary payload data is received from the server.

See "on_recv" for more details.

on_send

A code reference that will be triggered whenever data is sent to the remote WebSocket server.

See "on_send" for more details.

on_utf8

A code reference that will be triggered whenever text message is sent to the remote WebSocket server.

See "on_utf8" for more details.

origin

The origin of the request. See rfc6455 section on opening handshake

subprotocol

An array reference of protocols. They can be arbitrary identifiers and they are optionals.

See rfc6455 section on subprotocol

This can be changed later with "subprotocol"

uri

The uri for the remote WebSocket server.

version

The version of the WebSocket protocol. For example: draft-ietf-hybi-17

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.

connect

Initiate the handshake with the server and return the current object.

Before returning, this method will fork a separate process to listen to incoming messages in the background, so as to be non-blocking and return control to the caller.

    my $client = WebSocket::Client->new( 'wss://chat.example.org' )->connect ||
        die( WebSocket::Client->error );
    # Listener process runs now in the background
    $client->send( 'Hello !' );

connected

Sets or gets the boolean value representing whether the client is currently connected to the remote WebSocket server.

cookie

Set or get the Cookie header value.

Returns a scalar object

disconnect

Provided with an optional code and an optional reason, and this will close the connection with the server, and return the current object.

disconnected

Set or get a boolean value representing the connection status to the remote server socket.

There are 2 status: disconnecting and disconnected. The former is set when the client has issued a disconnection message to the remote server and is waiting for the server to acknowledge it, as per the WebSocket protocol, and the latter is set when the connection is effectively shut down.

disconnecting

Set or get the boolean value indicating the state of connection to the remote server socket.

This is set to a true value when the client has issued a disconnection notification to the server and is awaiting a response from the server, as per the rfc6455 protocol

do_pong

Set or get the code reference used to issue a pong. By default this is set to "pong"

frame_buffer

Set or get the frame buffer object.

handshake

Set or get the handshake object

ip

Set or get the ip of the remote server. This is set once a connection is established.

listen

This method is called by "connect" to listen to incoming message from the server. It is actually called twice. Once during the handshake and once the handshake is completed, the client forks a separate process in which it calls this method to listen to incoming messages.

max_fragments_amount

Takes an integer and set or get the maximum fragments amount.

max_payload_size

Takes an integer and set or get the maximum payload size.

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_binary

    $ws->on( binary => sub
    {
        my( $ws, $msg ) = @_;
        # Do something
    });

Event handler triggered when a binary message is received.

The current client object and the binary message are passed as argument to the event handler.

Any fatal error occurring in the callback are caught using try-catch with (Nice::Try)

on_connect

    $ws->on( connect => sub
    {
        my( $ws ) = @_;
        # Do something
    });

Event handler triggered when the connection with the server has been made and before any handshake has been performed.

The current client object is passed as argument to the event handler.

Any fatal error occurring in the callback are caught using try-catch with (Nice::Try), and if an error occurs, this method will set an error and return undef or an empty list depending on the context.

on_disconnect

    $ws->on( disconnect => sub
    {
        my( $ws, $code, $reason ) = @_;
        # Do something
    });

Event handler triggered before the connection with the server is closed.

The current client object, the code and optional reason are passed as argument to the event handler.

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.

on_error

    $ws->on( error => sub
    {
        my( $ws, $error ) = @_;
        # Do something
        print( STDERR "Error received upon handshake: $error\n" );
    });

Event handler triggered whenever an error occurs upon parsing of the handshake.

The current client object and the error object are passed as argument to the event handler.

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.

on_handshake

    $ws->on( handshake => sub
    {
        my( $ws ) = @_;
        # Do something
    });

Event handler triggered just before the handshake sequence is completed, but right after the handshake has been received from the server.

Be careful that this must return a true value, or else, it will fail the handshake.

The current client object is passed as argument to the event handler.

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.

on_ping

    $ws->on( ping => sub
    {
        my( $ws, $msg ) = @_;
        # Do something
        print( STDOUT "Received a ping from the server: $msg\n" );
    });

A code reference that will be triggered when a ping is received from the WebSocket server and right before a pong is sent back.

The current client object, and the possible message, if any, are passed as arguments to the event handler.

If the callback returns a defined, but false value, no pong will be issued in reply. A defined but false value could be an empty string or 0. This is designed in case when you do not waant to reply to the server's ping and thus inform it the client is still there.

It would probably be best to simply disconnect, but anyhow the feature is there.

See Mozilla documentation on ping and pong

See also "do_pong" to set the code reference to perform a pong in response.

Any fatal error occurring in the callback are caught using try-catch with (Nice::Try), and if an error occurs, this method will set an error and return undef or an empty list depending on the context.

on_pong

    $ws->on( pong => sub
    {
        my( $ws, $msg ) = @_;
        # Do something
        print( STDOUT "Received a pong from the server: $msg\n" );
    });

A code reference that will be triggered when a pong is received from the WebSocket server, most likely as a reply to our initial ping.

The event handler is then passed the current client object, and the optional message received in the original ping, if any.

See Mozilla documentation on ping and pong

See rfc6455 for more on this

Note that this handler is different from "do_pong", which is used to issue a pong back to the server in response to a ping received.

Any fatal error occurring in the callback are caught using try-catch with (Nice::Try), and if an error occurs, this method will set an error and return undef or an empty list depending on the context.

on_recv

Event handler triggered whenever a binary or text payload is received from the server.

The current frame object and the payload data are passed as arguments to the event handler.

    use JSON;
    $ws->on_recv(sub
    {
        my( $frame, $payload ) = @_;
        if( $frame->is_binary )
        {
            # do something
        }
        elsif( $frame->is_text )
        {
            # do something else
            my $hash = JSON::decode_json( $payload );
        }
    });

Any fatal error occurring in the callback are caught using try-catch with (Nice::Try), and if an error occurs, this method will set an error and return undef or an empty list depending on the context.

on_send

    $ws->on( send => sub
    {
        my( $ws, $msg ) = @_;
        # Do something
        print( STDOUT "Message sent to the server: $msg\n" );
    });

Event handler triggered whenever a message is sent to the remote server.

The current client object and the message are passed as argument to the event handler.

This callback is triggered on two occasions:

1. upon connecting, after the client has sent the handshake data to the server.
2. upon sending data to the server.

In either case, 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.

on_utf8

    $ws->on( utf8 => sub
    {
        my( $ws, $msg ) = @_;
        # Do something
        print( STDOUT "Message received from the server: $msg\n" );
    });

Event handler triggered whenever a text message is sent to the remote server.

The current client object and the message are passed as argument to the event handler.

Any fatal error occurring in the callback are caught using try-catch with (Nice::Try)

origin

Set or get the origin of the request as a Module::Generic::Scalar object.

ping

Send a ping to the WebSocket server and returns the value returned by "send". It passes "send" whatever extra argument was provided.

pong

Send a pong to the WebSocket server and returns the value returned by "send". It passes "send" whatever extra argument was provided.

recv

Will attempt to read data from the server socket and call all relevant event handlers. It returns the current object.

send

Sends data to the server socket and returns the current object. This will also trigger associated event handlers.

Returns the current object.

send_binary

Sends binary data to the server socket and returns the current object. This will also trigger associated event handlers.

Returns the current object.

send_utf8

Sends data to the server socket after having encoded them using "encode" in Encode and returns the current object. This will also trigger associated event handlers.

Returns the current object.

start

Start listening for possible events on the server socket.

Returns the current object.

subprotocol

Set or get an array object of WebSocket protocols and set the WebSocket header Sec-WebSocket-Protocol.

Returns a Module::Generic::Array object.

See rfc6455 for more information

shutdown

Shut down the socket by sending a "shutdown" in IO::Socket command and sets the "disconnected" status to true.

Returns the current object.

socket

Set or get the remote server socket. This expects the object to be a IO::Socket instance, or an inheriting package.

timeout

Set or get the timeout used when issuing messages to the remote server, such as close and waiting for the server response.

uri

Returns the uri of the server uri.

See rfc6455 specification

version

The WebSocket protocol version being used, such as draft-ietf-hybi-17

See rfc6455 about suport for multiple versions

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::Server, rfc6455

COPYRIGHT & LICENSE

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.