WebSocket Node.js No Library (Vanilla JS)

Gustavo Graeff
2 min readDec 2, 2021

--

Hello Medium, after some while I’m here again.

In the last days, I’ve been studying about Network Socket.
There are a lot of different npm packages that make its implementation easier and faster, like socket.io, ws, websocket, etc.

But the major information and examples over the internet are using them, so what if we want to understand more than just the ready abstractions. How and why it works?

It’s definitely not an easy task, some hours of searching and all the Vanilla JS examples were not clear enough… Why the algorithm is that complicated, why is it written like that, where does the information come from?

I couldn’t get my head around this, a lot of things happening with a few comments and bad naming were totally confused.

So I decided to get more time and understand even more about network protocols, especially from TCP (Transmission Control Protocol) and WebSocket official docs.

Some hours later, I finally came up with clear information and really understood how the code should behave and I’m proud to share it with you all. Hoping to be clear enough and help other curious minds.

Check the GitHub project: https://github.com/gustavograeff/vanilla-js-web-socket.

I’ll explain some important parts, splitting the code:

The getValidHandShakeKey creates the sha1 hash required to validate the communication.

The writeSocketValidUpgrade builds and writes the right headers that the WebSocket protocol needs.

The sendClientDataFrame creates the buffer and writes it into the WebSocket, sending this data to all clients which are listening to the connection.

The handleClientWebSocketData read the data coming from Client to Server, a Buffer which is always masked and have to be decoded, based on the algorithm from the official docs.

That’s all folks, I really hope you all enjoy these tips a lot, and feel free to make any questions/suggestions in the comments below.
See you soon!

--

--