Using WebSockets and Handshake with Node js - 5G Software

June, 09 2021



WebSockets
WebSockets is a protocol built on top of TCP. They hold the connection to the server open so that the server can send information to the client, even in the absence of a request from the client. WebSockets allow for bi-directional, “full-duplex” communication between the client and the server by creating a persistent connection between the two.

Action Cable can be run on a stand-alone server, or we can configure it to run on its own processes within the main application server. Action Cable uses the Rack socket hijacking API to take over control of connections from the application server. Action Cable then manages connections internally, in a multithreaded manner, layering as many channels as you care to define over that socket connection.

For every instance of your application that spins up, an instance of Action Cable is created, using Rack to open and maintain a persistent connection, and using a channel mounted on a sub-URI of your main application to stream from certain areas of your application and broadcast to other areas.

Action Cable offers server-side code to broadcast certain content (think new messages or notifications) over the channel, to a subscriber. The subscriber is instantiated on the client-side with a handy JavaScript function that uses jQuery to append new content to the DOM.

Handshake
All Web socket requests start out with a handshake. This is to make sure that both the client and the server both understand that Web. Once a WebSocket connection is established, HTTP is no longer used. Instead, data is exchanged via the WebSocket protocol. Frames are the basic unit of the WebSocket protocol. The WebSocket protocol is frame-based

Whenever you ask your web browser to send data over WebSocket or ask your server to respond, the data is broken up into a series of chunks in each of those chunks is wrapped in some metadata to make a frame.