Using JavaScript we can traditionally send JSON or XML as strings. However, HTML5 allows applications to work with binary data to improve performance. WebSockets supports two kinds of binary data
Binary Large Objects (
blob
)arraybuffer
A WebSocket can work with only one of the formats at any given time.
Using the binaryType
property of a WebSocket, you can switch between using blob or arraybuffer
:
websocket.binaryType = "blob"; // receive some blob data websocket.binaryType = "arraybuffer"; // now receive ArrayBuffer data
The following code snippet shows how to display images sent by a server using WebSockets.
Here is a code snippet for how to send binary data with WebSockets:
websocket.binaryType = 'arraybuffer';
The preceding code snippet sets the binaryType
property of websocket
to arraybuffer
.
websocket.onmessage = function(msg) { var arrayBuffer = msg.data; var bytes = new Uint8Array(arrayBuffer); var image = document...