Anandi Sheladiya
Contact
  • About Anandi
  • SKILLS & EXPERIENCE
    • Frontend
      • ReactJS
      • Next.js – The React Framework for Production
      • ChartJS / D3.JS / Fabric JS
      • Three.JS: The JavaScript Library for 3D Graphics
      • HTML/CSS/JS/Tailwind CSS/Bootstrap
      • Material UI – The Ultimate React UI Framework
      • ShadCN/UI – The Modern UI Library for React
    • Backend
      • NodeJS & ExpressJS
      • Web3.JS
      • Python & Django
      • GoLang
      • TypeScript
    • Database
      • PostgreSQL
      • MongoDB - NOSQL Database
      • MySQL
    • API
      • REST API
      • GraphQL API
      • RPC (Remote Procedure Call)
      • WebSocket
    • Solidity
    • Layer 1 Blockchain
      • Ethereum
      • Solana
      • Bitcoin
      • Hyperledger
      • Binance
      • Avalanche
      • Cardano
      • Polkadot
      • Near Protocol
      • Algorand
      • TON (Telegram Open Network)
    • Optimistic Rollups (L2 on Ethereum)
      • Arbitrum
      • Base
      • Mantle
    • ZK-Rollups (L2 on Ethereum)
      • zkSync Era
      • Polygon zkEVM
    • Wallet Integration
      • Reown Appkit
      • Rainbow Walletkit
      • Web3 Modal
      • WalletConnect
      • Wagmi
      • Metamask & Safewallet SDKs
    • Web3 SDKs & API Providers
      • Alchemy
      • Moralis
      • QuickNode
      • BitQuery API & Stream
      • ThirdWeb
      • Infura
      • Li.Fi
      • 1Inch API
      • Uniswap API
      • OpenZeppelin
    • Web3 Middleware/ UX Infrastructure Platform
      • Biconomy
      • Pimlico
      • Alchemy AA
      • Safe (formerly Gnosis Safe)
      • ZeroDev
    • On Chain Trading Platform & Telegram Bot
      • Bullx
      • Wave Bot
      • GMGN
      • Shuriken
      • Magnum Trade
      • Trojan
  • PROTOCOLS
    • ERCs & EIPs
      • ERC-20: The Standard for Fungible Tokens
      • ERC-721: The Standard for Non-Fungible Tokens (NFTs)
      • ERC 4337
      • ERC 6551: Token Bound Accounts (TBA)
      • ERC 7702
      • EIP 4844 (Proto-Danksharding)
      • Ethereum Pectra
  • ARTICLES
    • Medium
Powered by GitBook
On this page
  • What is WebSocket?
  • How WebSockets Work
  • WebSocket Architecture
  • WebSocket Example (Node.js & JavaScript)
  • WebSocket Events:
  • WebSocket Use Cases
  • Disadvantages of WebSockets
  • When to Use WebSockets?
  • Conclusion

Was this helpful?

  1. SKILLS & EXPERIENCE
  2. API

WebSocket

What is WebSocket?

WebSocket is a communication protocol that provides full-duplex, real-time communication between a client and a server over a single TCP connection. Unlike traditional HTTP, which follows a request-response model, WebSockets enable continuous bidirectional communication, making them ideal for chat applications, live notifications, gaming, and stock market updates.

How WebSockets Work

  1. Handshake – The client sends an HTTP request to upgrade the connection to WebSocket.

  2. Connection Establishment – The server accepts the request, and both establish a persistent WebSocket connection.

  3. Bidirectional Communication – The client and server can now send messages anytime without waiting for a response.

  4. Connection Closure – Either side can close the connection when needed.

WebSocket Architecture

  • Client – A web browser or app initiating a WebSocket connection.

  • WebSocket Server – Manages connections and routes messages.

  • Message Transport – The WebSocket protocol sends messages over a single connection.

WebSocket Example (Node.js & JavaScript)

Let's create a WebSocket server and a WebSocket client.

1. Install WebSocket Library

Run the following command to install WebSocket support:.

npm install ws
  1. Create a WebSocket Server (Node.js)

const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (socket) => {
    console.log('New client connected');

    socket.on('message', (message) => {
        console.log(`Received: ${message}`);
        socket.send(`Server received: ${message}`);
    });

    socket.on('close', () => {
        console.log('Client disconnected');
    });
});

console.log('WebSocket server is running on ws://localhost:8080');
  1. Create a WebSocket Client (Browser JavaScript)

const socket = new WebSocket('ws://localhost:8080');

socket.onopen = () => {
    console.log('Connected to WebSocket server');
    socket.send('Hello, Server!');
};

socket.onmessage = (event) => {
    console.log(`Message from server: ${event.data}`);
};

socket.onclose = () => {
    console.log('Disconnected from WebSocket server');
};

WebSocket Events:

Event
Description

onopen

Triggered when the WebSocket connection is established.

onmessage

Triggered when a message is received from the server.

onerror

Triggered when an error occurs.

onclose

Triggered when the connection is closed.

WebSocket Use Cases

  • Live Chat Applications – Instant messaging with real-time updates.

  • Stock Market Feeds – Live updates of stock prices.

  • Online Gaming – Multiplayer games with real-time interactions.

  • Live Sports Scores – Streaming real-time game updates.

  • Collaboration Tools – Google Docs-style real-time editing.

Disadvantages of WebSockets

  • Firewall Issues – Some corporate networks block WebSocket connections.

  • Scalability – Managing multiple open WebSocket connections can be resource-intensive.

  • Complexity – More difficult to implement than traditional HTTP requests.

When to Use WebSockets?

  • Need real-time updates (Chat apps, stock tickers, notifications).

  • Frequent two-way communication (Gaming, live streaming).

  • Reduce latency (Instant response without polling the server).

Conclusion

WebSockets provide an efficient, low-latency communication channel for real-time applications. They outperform HTTP when continuous, bidirectional data flow is required.

PreviousRPC (Remote Procedure Call)NextSolidity

Last updated 3 months ago

Was this helpful?