phasync
WebSocket / sendBinary

Method

WebSocket::sendBinary

Send a binary message; nothing happens once the connection is closed.

Description#

public WebSocket::sendBinary(
    string $data
): void

Parameters#

$data string
The message

Examples#

Example 1A binary message
use Swerve\ClientRequest;
use Swerve\RequestHandler;
use Swerve\WebSocket;

$app = new RequestHandler(function (ClientRequest $request) {
    WebSocket::from($request, function (WebSocket $ws) {
        $ws->sendBinary(pack('nN', 1, 42));     // bytes, not text: any value
        $ws->send('text must be UTF-8');
    });
});

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

< (binary) 00010000002a
< text must be UTF-8
< close 1000
Example 2
$ws->sendBinary(pack('N', 42));

See also#

  • WebSocket::sendSend a text message; nothing happens once the connection is closed.