Method
WebSocket::run
For adapters whose own code already sent the 101 (such as swerve-psr15's bridge, after its middleware decided the headers): run $callback on $connection as WebSocket::upgrade does, with the same close codes and cancellation. $connection need be no more than a Duplex: read(), write(), end() and close() are all this uses.
Description#
public static WebSocket::run(
Duplex $connection,
callable $callback,
?string $subprotocol = null,
int $maxMessage = self::MAX_MESSAGE
): voidParameters#
- $connection Duplex
- $callback callable
- $subprotocol ?string = null
- $maxMessage int = self::MAX_MESSAGE
- See upgrade()
Examples#
use Swerve\ClientRequest;
use Swerve\RequestHandler;
use Swerve\WebSocket;
// For code that sends the 101 itself: run() takes over the connection after it
$app = new RequestHandler(function (ClientRequest $request) {
$decision = WebSocket::handshake($request->getMethod(), $request->getProtocolVersion(), $request->getRequestHeaders(), false);
$request->sendResponseHeaders(101, $decision->headers);
WebSocket::run($request, function (WebSocket $ws) {
foreach ($ws as $message) {
$ws->send(strtoupper($message));
return;
}
});
});
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', ['shout']);Output
HTTP/1.1 101 Switching Protocols upgrade: websocket connection: Upgrade sec-websocket-accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Server: Swerve > shout < SHOUT < close 1000