phasync
WebSocket / upgrade

Method

WebSocket::upgrade

For framework adapters: send the 101 with the headers an adapter decided, and run $callback on the open connection.

Description#

public static WebSocket::upgrade(
    ClientRequest $request,
    array $headers,
    callable $callback,
    int $maxMessage = self::MAX_MESSAGE
): void

What WebSocket::from does once WebSocket::handshake accepted: the headers are sent as given (the adapter's middleware may have added some), nothing is validated again, and the subprotocol is the one in sec-websocket-protocol. Returns when the connection has closed. Applications use from() and don't call this.

Parameters#

$request ClientRequest
$headers array
The 101 response's headers, including sec-websocket-accept
$callback callable
$maxMessage int = self::MAX_MESSAGE
The largest message received, in bytes; a larger one closes with 1009

Examples#

Example 1An adapter's upgrade
use Swerve\ClientRequest;
use Swerve\RequestHandler;
use Swerve\WebSocket;

// What a framework adapter does: decide with handshake(), let middleware add headers, then upgrade()
$app = new RequestHandler(function (ClientRequest $request) {
    $decision = WebSocket::handshake($request->getMethod(), $request->getProtocolVersion(), $request->getRequestHeaders(), false);
    if (!$decision->accepted()) {
        $request->sendResponseHeaders($decision->status, $decision->headers);
        $request->write($decision->body);

        return;
    }
    $headers = $decision->headers + ['x-served-by' => 'my-framework'];   // middleware decorates
    WebSocket::upgrade($request, $headers, function (WebSocket $ws) {
        $ws->send('upgraded by the adapter');
    });
});

if (debug_backtrace()) {
    return $app;   // swerve loads this file: it is the application's swerve.php
}

// Run directly: serve the application with swerve, and talk to it as a browser would
require __DIR__ . '/../serve.php';
websocket(__FILE__, '/socket', []);
Output
HTTP/1.1 101 Switching Protocols
upgrade: websocket
connection: Upgrade
sec-websocket-accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
x-served-by: my-framework
Server: Swerve

< upgraded by the adapter
< close 1000