NAME

Unblock::WebSocket::Client - client side of an established WebSocket connection

SYNOPSIS

use Unblock::WebSocket::Client;

# The opening HTTP handshake must already be complete.
my $ws = Unblock::WebSocket::Client->new(
    on_message => sub {
        my ($ws, $message, $type) = @_;
        print "Received $type: $message\n";
    },
);

$ws->send_text('hello');

# Manual mode: move these bytes to the transport write queue.
while ($ws->want_write) {
    $host->write($ws->output);
}

# When the transport receives new WebSocket bytes:
$ws->input($bytes);

DESCRIPTION

Client encodes and decodes WebSocket frames for the client end of a connection. It masks outgoing messages as required by RFC 6455.

It does not open a socket, send an HTTP request, or run an event loop.

First create an HTTP request with "client_request" in Unblock::WebSocket::Handshake, send it using your HTTP implementation, and validate the response. Then create Client:

my $ws = Unblock::WebSocket::Client->new(
    %{ $handshake->connection_options },
    on_message => sub { ... },
);

The connection options carry negotiated compression, if any.

CHOOSING OUTPUT MODE

Without a transport option, use input($bytes) for incoming bytes and output() while want_write() is true for outgoing bytes. The caller must preserve outgoing byte order.

For attached output, supply a host object:

my $ws = Unblock::WebSocket::Client->new(
    transport => $host,
    on_message => sub { ... },
);

The host must implement unblock_send($bytes), unblock_finish() and unblock_abort($reason). The engine sends outgoing buffers to that host automatically. Its unblock_send() must accept every byte or throw. A defined false return means it accepted every byte but is congested; call $ws->resume_output() once it can accept more.

The host owns the socket, its write queue, TLS, EOF, and timers. Use input_eof() when its read side ends or transport_error($reason) when it fails. Do not call output() with a host attached.

MESSAGES AND CALLBACKS

send_text($text) sends a UTF-8 text message. send_binary($bytes) sends a binary message. ping($payload) sends a Ping; received Ping frames are answered automatically.

on_message receives ($ws, $payload, $type) where $type is text or binary. Other callbacks are on_ping, on_pong, on_close, on_error, and on_drain.

close(code => 1000, reason => 'done') starts the WebSocket Close handshake. It is not an immediate socket shutdown.

A false return from a send method still means the message was accepted. Pause producing messages until on_drain fires.

See "ESTABLISHED CONNECTION API" in Unblock::WebSocket for all options and methods, and docs/INTEGRATION.md for detailed host rules.