How do you send data over a WebSocket connection?

Answer

Data is sent over WebSocket using the ws.send(data) method, which accepts three data types: String (text message, most common), ArrayBuffer (raw binary data), and Blob (binary large object, useful for files). For structured data, serialize to JSON: ws.send(JSON.stringify({ type: 'message', payload: 'Hello' })). The server then parses the JSON string. For binary protocols (images, audio streams, game state), use ArrayBuffer for efficiency — binary avoids the overhead of base64 encoding. Always check ws.readyState === WebSocket.OPEN before calling send(), as sending on a closed connection throws an error. You can also monitor ws.bufferedAmount to check how much data is queued but not yet sent to the network.