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

UniEvent::WebSocket::Client - Asynchronous websocket client

SYNOPSIS

    # Client
    my $client = UniEvent::WebSocket::Client->new;
    $client->connect("ws://myserver.com:12345");
    $client->connect_callback(sub {
        my ($client, $connect_response) = @_;
        if ($connect_response->error) { ... }
        $client->send_text("hello");
    });
    $client->message_callback(sub {
        my ($client, $message) = @_;
        say $message->payload;
        $client->close(UniEvent::WebSocket::CLOSE_DONE);
    });
    $client->peer_close_callback(sub {
        my ($client, $message) = @_;
        say $message->close_code;
        say $message->close_message;
    });
    
    ...
    UE::Loop->default->run;

DESCRIPTION

UniEvent::WebSocket::Client represents a websocket client connection to server. You should use this class to connect to websocket server.

It is inherited from the basic connection class UniEvent::WebSocket::Connection, so the most API documented there.

METHODS

new([\%config = default config], [$loop = default loop])

Create websocket client for a given config and UniEvent::Loop. This client will work when you run specified event loop.

See configure() method for details on what config supports.

configure(\%config)

Configures websocket client with new config. Can be called at any time, even if connection is already established; applied immediately.

config should be a hash reference with the following fields:

anything that UniEvent::WebSocket::Connection's configure() supports.
tcp_nodelay [=false]

If true, enables tcp nodelay feature.

    $client->configure({
        tcp_nodelay    => 1,
        max_frame_size => 1000,
    });

connect($request)

Starts connection process to the server.

$request must be an UniEvent::WebSocket::ConnectRequest object or hashref that its constructor supports. See UniEvent::WebSocket::ConnectRequest for possible options.

All the needed data for connectig are in the request.

connect($uri)

The same as

    $client->connect({uri => $uri});

connect($host, [$is_secure = false], [$port = 0])

The same as

    $client->connect($uri)

Where $uri is constructed according to $host, $is_secure (result in "ws" or "wss" scheme) and $port.

connect_callback($sub)

connect_event()

Callbacks set via these methods will be invoked when client establishes connection and completes websocket handshake.

After this moment client object can be used for sending and receiving data.

Callback signature:

    my ($client, $response) = @_;
    

Where $response is an Protocol::WebSocket::Fast::ConnectResponse object.

Any error may be read via $response->error() method, see Protocol::WebSocket::Fast::ConnectResponse.

See "EVENT CALLBACKS" in UniEvent for differences between _callback and _event versions of methods.