How do you handle binary data over WebSockets?

Answer

WebSocket natively supports binary frames (opcode 0x2) in addition to text frames. On the client, set ws.binaryType = 'arraybuffer' (default is blob) to receive binary data as ArrayBuffer objects. Sending binary: ws.send(arrayBuffer) or ws.send(blob). Use cases: transmitting images, audio samples, game state encoded in a compact binary format (reducing bandwidth vs. JSON). For example, encoding game position as a Float32Array (Float32Array([x, y, rotation])) sends 12 bytes vs. ~30 bytes of JSON. On the server (Node.js ws library), binary messages arrive as Buffer objects. Protobuf or MessagePack are common binary serialization formats used with WebSocket binary frames, offering significant bandwidth savings over JSON for high-frequency or large messages.