Core\Socket::sendBytes
Sends one binary message to the client on the WebSocket connection your script is running for.
It works like send(), but the message is bytes instead of text. The bytes are sent as they are, and nothing checks them, so this is the method for images, compressed data and packed numbers. The client receives them as one binary message. sendBytes() returns nothing.
sendBytes() waits until the message is written, but not forever. If the client stops reading and the message cannot be written in time, it throws a RuntimeError. Outside a connection, it throws a LogicError.
The examples below send a few bytes, send a binary message back to the client, and send sensor readings packed as bytes.
Parameters
$framebytesThe bytes to send. They are sent as they are, and nothing checks them.
Return value
Returns void. Nothing.
Errors
LogicErrorThe script is not running for a connection, so there is no client to send to.RuntimeErrorThe connection broke, or the client stopped reading and the message could not be written in time, as forsend.
Examples
Sending a few bytes
<?nvs// Shows how to send a few bytes to the client as one binary message.
// The `.nvsp` file beside this example plays a client that sends nothing and closes.Core\Socket $conn = Core\Socket::current();
// Each `sent bytes:` line in the output is a binary message the client received,// written as hexadecimal digits. This prints `sent bytes: 4e 56 53`.$conn->sendBytes('NVS' as bytes);sent bytes: 4e 56 53Sending a message back
<?nvs// Shows a connection that sends every message back to the client, binary or text.
// The `.nvsp` file beside this example plays the client.// It sends one binary message and one text message, then closes the connection.Core\Socket $conn = Core\Socket::current();
// `bytes()` is `null` for a text message, so the check picks the right method.// This prints `sent bytes: 89 50 4e 47` and then `sent: ping`.?Core\Socket\Message $message = $conn->receive();while ($message != null) { ?tainted bytes $octets = $message->bytes(); if ($octets != null) { $conn->sendBytes($octets); } else { $conn->send($message->text() ?? ''); } $message = $conn->receive();}sent bytes: 89 50 4e 47sent: pingSending sensor readings
<?nvs// Shows a connection that sends each sensor reading to the client as a small binary message.
// The `.nvsp` file beside this example plays a client that sends nothing and closes.Core\Socket $conn = Core\Socket::current();
// `Core\Bytes::pack` writes the sensor number in two bytes and the temperature in four bytes.// The first line is `sent bytes: 00 01 00 00 00 15`: sensor 1 and a temperature of 21.array<int> $temperatures = [21, 22, 19];uint $sensor = 1;foreach ($temperatures as int $temperature) { $conn->sendBytes(Core\Bytes::pack('nN', $sensor, $temperature)); $sensor = $sensor + 1;}sent bytes: 00 01 00 00 00 15sent bytes: 00 02 00 00 00 16sent bytes: 00 03 00 00 00 13