phasync
WebSocket / end

Method

WebSocket::end

Close the connection: send a close frame with $code and $reason and end the sending side, once.

Description#

public WebSocket::end(
    int $code = 1000,
    string $reason = ''
): void

receive() returns null from then on, and $onClose fires once, with the code and reason of whoever said goodbye first. The connection is closed when the client closes its side, or after a moment without. Returning from the callback does the same with 1000. May be called from any coroutine; later calls do nothing.

Parameters#

$code int = 1000
The close code (RFC 6455, section 7.4): 1000 is a normal closure; 1005, 1006 and the other codes that never go on the wire are refused
$reason string = ''
The close frame's reason text: UTF-8, at most 123 bytes

Errors / Exceptions#

ExceptionWhen
ValueErrorWhen the code may not be sent or the reason is too long or not UTF-8

Examples#

Example 1A close code of your own
use Swerve\ClientRequest;
use Swerve\RequestHandler;
use Swerve\WebSocket;

$app = new RequestHandler(function (ClientRequest $request) {
    WebSocket::from($request, function (WebSocket $ws) {
        $ws->send('guess a number');
        foreach ($ws as $guess) {
            if ('7' === $guess) {
                $ws->end(4000, 'you win');       // 4000-4999: codes of your own application
            } else {
                $ws->send('no');
            }
        }
    });
});

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__, '/game', ['3', '7']);
Output
HTTP/1.1 101 Switching Protocols
upgrade: websocket
connection: Upgrade
sec-websocket-accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Server: Swerve

> 3
> 7
< guess a number
< no
< close 4000 you win
Example 2
$ws->onMessage->listen(function (string $data) use ($ws) {
    if ('bye' === $data) {
        $ws->end(1000, 'bye');
    }
});