phasync
WebSocket / from

Method

WebSocket::from

Answer the handshake and run $callback on the open connection; returns when the connection has closed.

Description#

public static WebSocket::from(
    ClientRequest $request,
    callable $callback,
    array $subprotocols = [],
    ?array $origins = null,
    int $maxMessage = self::MAX_MESSAGE
): void

A request that is no WebSocket handshake is answered as WebSocket::accept says, and the callback is not called. Returning from the callback closes with 1000, throwing closes with 1011 and is logged by swerve; the client leaving cancels it.

Parameters#

$request ClientRequest
$callback callable
$subprotocols array = []
See accept()
$origins ?array = null
See accept()
$maxMessage int = self::MAX_MESSAGE
See accept()

Examples#

Example 1Listen to messages, push from a subscription
use Swerve\ClientRequest;
use Swerve\RequestHandler;
use Swerve\Swerve;
use Swerve\WebSocket;

$app = new RequestHandler(function (ClientRequest $request) {
    WebSocket::from($request, function (WebSocket $ws) {
        $ws->onMessage->listen(function (string $data) {     // inbound: events
            Swerve::publish('chat', $data);                  // to every worker's subscribers
        });
        foreach (Swerve::subscribe('chat') as $out) {        // outbound: plain sequential code
            if ('/quit' === $out) {
                return;
            }
            $ws->send("someone said: $out");
        }
    });
});

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__, '/chat', ['hi all', 'anyone here?', '/quit']);
Output
HTTP/1.1 101 Switching Protocols
upgrade: websocket
connection: Upgrade
sec-websocket-accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Server: Swerve

> hi all
> anyone here?
> /quit
< someone said: hi all
< someone said: anyone here?
< close 1000
Example 2
WebSocket::from($request, function (WebSocket $ws) {
    foreach ($ws as $message) {
        $ws->send(strtoupper($message));
    }
}, origins: ['https://example.com']);