JoinDownload
This is drafted post. Please setdraft: falsein this .mdx file once ready to be published.

How to send Binary Data in WebSocket

3 Min Read

Vyom Srivastava

Sending binary data can be very beneficial in terms of optimization. This can be much and more beneficial in the case of multiple users where a lot of users are connected in the same arena to sync the data.

You might be wondering how Binary Data works right? Let’s go back to the fundamentals of the computer system. When you were a kid, you were taught that the data is stored in computers in binary form and even when you transfer the data, it is being transferred into binary form not JSON or normal text. Now I won’t go much deep into why computers use binary format but I can explain why it is faster.

Let’s take an example of REST APIs. You know that REST API most of the time sends data in JSON or in some cases it could be URL encoded. Now when they send the data, it is first encoded into a binary form so that it can be transferred and when you receive that data the web first decodes the data back to its original form that is JSON, and then sends it to your application. All of this calculation happens in the background. You don’t see all of this because it doesn’t happen at the application level.

Now here, you should be able to join the dots. When you’re passing the data in binary form why does it even need to encode the data before sending it? While the same is the case at the receiving end, the data doesn’t need to be decoded here. So you see, it saved some time here and which is why it is faster than the normal data transfer.

To make this possible in javascript we have some predefined functions:

Float32Array()

It takes an array as a parameter and converts them into a 32-bit float before storing them in the memory.

For example:

var x = new Float32Array([17, -45.3]);
var y = new Float32Array(x);
console.log(x[0]);
console.log(x[1]);
console.log(x.length);
x[0] = -2;
console.log(y[0]); // y is not modified

The output will be:

17
-45.29999923706055
2
17

Int32Array()

Similar to the above one, this also takes an array as the parameter and converts them into a 32-bit integer value.

For example:

var x = new Int32Array([17, -45.3]);
console.log(x[0]);
console.log(x[1]);
console.log(x.length);

BigInt32Array()

Similar to the above one, this also takes an array as the parameter and converts them into a 32-bit big integer value.

How to process Binary works in JavaScript?

We use Arraybuffer to create a binary data buffer. This buffer is used to create a data view buffer which can be used to create typical buffers of 8, 16, 32, 64 bits, and so on. We can not directly edit this array buffer. Instead, we have to first create a typed array that can represent the buffer in its typical format.

The two most widely used values for buffet type are Arraybuffer and blob out of which Arraybuffer is the preferred method as it works faster than the blog and works perfectly with synchronous APIs.

Now let’s try to send binary data in NodeJS with WebSocket:

Prerequisites

  • Basic knowledge of NodeJS
  • ws package

Step -1: Environment setup:

Now create a folder named binary-ws and open it:

mkdir binary-ws
cd binary-ws

Now once you’re in the folder initialize a project:

npm init

Once done let's install the package:

npm install ws

Step -2: Server.js setup:

Now create a file server.js and open it in your favorite code editor .

Once done, and paste the below code:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8000 });
wss.on('connection', function connection(ws) {
console.log("Connected")
var arr1 = new Float32Array(45);
for (var i = 0; i < arr1.length; ++i)
arr1[i] = (i + 100) / 7;
var arr2 = new ArrayBuffer(8);
var view = new Uint8Array(arr2);
for(var i = 0; i < 8; i++)
view[i] = i * 17;
console.log(arr2)
ws.send(arr2);
});

Code Explanation:

We’re importing the required package ws and then creating a WebSocket server at port 8000. Now on the connection event, we’re printing a message on the console which we can use to check if the WebSocket is connected or not. After that, we’re creating an array of 32-bit float data. Then we’re passing it in the Arraybuffer() and using a view to parse the data. After that ws.send is returning it as the response.

Step -3: Testing the WebSocket:

Now open the FireCamp app and select the WebSocket option from the menu. Now in the URL, paste this URL: ws://localhost:8000/websocket and click the Connect button.

In the message, pane passes this array: [ 21, 32, 32, 34 ] and select ArrayBuffer as data type and then select Float32Array. Once you press the run button, you’ll see the below output:

ws-binary

Final Words:

We have learned how we can work with binary data in WebSockets, and test it in the FireCamp app. The binary data can help to reduce the latency but it can not be used everywhere. It has some specific applications and depends on the project's requirements as well.

CONTENT
Float32Array()Int32Array()BigInt32Array()
How to process Binary works in JavaScript?PrerequisitesStep -1: Environment setup:Step -2: Server.js setup:Step -3: Testing the WebSocket:Final Words:

Links

DownloadDocChange LogsCookiesTerms & ConditionsPrivacy PolicyContact Us

Apps & Integrations

HTTPGraphQLWebsocketSocketIO

Firecamp Newsletter