Websocket

Neha SawantNeha Sawant
3 min read

Backend communication refers to how the backend (server-side) of an application interacts with other systems, services, or databases to perform operations, process data, or respond to client (frontend) requests

Types of communication

Synchronous (Strong coupling)

  1. HTTP (REST/GraphQL)

  2. Websocket (debatable if sync or async)

Asynchronous (Weak coupling)

  1. Messaging queues

  2. Pub subs

  3. Server-Sent Events

  4. Websocket (debatable if sync or async)

Websockets

WebSockets provide a way to establish a persistent, full-duplex communication channel over a single TCP connection between the client (typically a web browser) and the server.

notion image

Use Cases for WebSockets:

  • Real-Time Applications: Chat applications, live sports updates, real-time gaming, and any application requiring instant updates can benefit from WebSockets.

  • Live Feeds: Financial tickers, news feeds, and social media updates are examples where WebSockets can be used to push live data to users.

  • Interactive Services: Collaborative editing tools, live customer support chat, and interactive webinars can use WebSockets to enhance user interactio

Good example - https://www.binance.com/en/trade/SOL_USDT?type=spot

Why not use HTTP/REST? Why do you need ws?

Limitations of HTTP/REST:

  1. One-way communication

    • The client (browser/app) makes a request. The server can only respond—it can’t initiate communication.
  2. No real-time updates

    • For things like chat, live notifications, or stock prices, you’d need to constantly poll the server (send repeated requests), which is inefficient.
  3. Stateless

    • Each request is independent; the server doesn't remember previous interactions without extra effort (e.g., sessions or tokens).

Why Use WebSockets (ws)?

  • Real-time communication

    • Perfect for apps like chat, multiplayer games, live dashboards, collaborative editors (like Google Docs), etc.
  • Low latency, efficient

    • No need for constant HTTP requests; once connected, data flows instantly as needed.
  • Two-way interaction

    • The server can send data anytime, without waiting for the client to ask.

notion image

Websockets in Node.js

There are various libraries that let you create a ws server (similar to how express lets you create an HTTP server)

  1. https://www.npmjs.com/package/websocket

  2. https://github.com/websockets/ws

  3. https://socket.io/

Create websocket server:

  • Initialize an empty Node.js project
npm init -y
  • Add tsconfig to it
npx tsc --init
npm install typescript
  • Update tsconfig
"rootDir": "./src",
"outDir": "./dist",

Create folders src and create file inside it i.e index.ts

  • change in package.json
"scripts":
{
"dev": "tsc -b && node ./dist/index.js"
},

now your all ts file will save in src folder and js file will save in dist folder.

  • Install ws
npm i ws @types/ws

index.ts:

import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

//event handler
wss.on('connection', function connection(socket) {

    console.log("user connected")
    socket.send('Hello');

    setInterval(() => {
        socket.send("current price is :" + Math.random());
    },500)

    socket.on("message", (e) =>{
    console.log(e.toString())
    })

});

enter all code. run program in terminal with npm run dev command.

open postman (client)

server to client postman -> websocket -> url:ws://localhost:8080 -> send

client to server postman -> connect url -> type message-> send it. -> it will print on vs code.

0
Subscribe to my newsletter

Read articles from Neha Sawant directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Neha Sawant
Neha Sawant