phasync
WebSockets and SSE / WebSocketHandshake

Class

WebSocketHandshake

The decision of WebSocket::handshake: the answer to a WebSocket handshake.

Introduction#

Adapter-facing: a framework adapter builds its own response from it. Accepted (101 === $status), $headers are those of the 101 response and $subprotocol is the one chosen. Refused (426, 400 or 403), $headers and $body are the complete final response, as swerve itself answers.

Class synopsis#

final class WebSocketHandshake {
    /* Methods */
    public WebSocketHandshake::__construct(
        int $status,
        array $headers,
        string $body = '',
        ?string $subprotocol = null
    )
    public WebSocketHandshake::accepted(): bool
}

Properties#

NameTypeDescription
$statusreadonly int
$headersreadonly array
$bodyreadonly string
$subprotocolreadonly ?string

Methods#

MethodDescription
__constructThe decision as WebSocket::handshake makes it.
acceptedWhether the connection may be upgraded: the status is 101.

Examples#

Example 1Accepted and refused
use Swerve\WebSocket;

$headers = [
    'upgrade'               => ['websocket'],
    'connection'            => ['Upgrade'],
    'sec-websocket-key'     => ['dGhlIHNhbXBsZSBub25jZQ=='],
    'sec-websocket-version' => ['13'],
];

$accepted = WebSocket::handshake('GET', '1.1', $headers, false);
var_dump($accepted->accepted());
print_r($accepted->headers);            // the 101 response's headers

$refused = WebSocket::handshake('POST', '1.1', $headers, true);
var_dump($refused->accepted());
echo $refused->status, ' ', $refused->body, "\n";   // the complete final response
print_r($refused->headers);
Output
bool(true)
Array
(
    [upgrade] => websocket
    [connection] => Upgrade
    [sec-websocket-accept] => s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
)
bool(false)
400 Not a WebSocket handshake
Array
(
    [sec-websocket-version] => 13
    [content-type] => text/plain
    [content-length] => 25
)