MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
WebSockets for Real-Time Bidirectional Communication0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
11.1WebSockets for Real-Time Bidirectional Communication11.2Server-Sent Events (SSE)11.3Fetch Interceptors & Request Middleware11.4GraphQL Queries, Mutations & Subscriptions
HomeTutorialsJavaScript for AdvancedWebSockets for Real-Time Bidirectional Communication
Server-Sent Events (SSE)

WebSockets for Real-Time Bidirectional Communication

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

WebSockets for Real-Time Communication in Modern JavaScript

Traditional HTTP follows a unidirectional request-response paradigm: the client asks, the server answers, and the connection closes. For real-time applications (chat apps, collaborative whiteboards, live trading dashboards, multiplayer gaming), polling the server with HTTP requests wastes bandwidth. WebSockets provide a persistent, full-duplex, bidirectional communication channel over a single TCP connection.


1. HTTP Polling vs. WebSockets

1HTTP Polling (Inefficient):
2 Client ──► GET /status ──► Server (200 OK)
3 Client ──► GET /status ──► Server (304 Not Modified)
4 Client ──► GET /status ──► Server (304 Not Modified) (High overhead: headers sent every second!)
5 
6WebSocket (Persistent Full-Duplex):
7 Client ──► HTTP Upgrade Handshake ──► Server
8 ══════════════════════════════════════════════════
9 Client ◄──────── Bidirectional TCP ────────► Server
10 (Zero HTTP headers! Raw message frames with ~2 bytes framing overhead!)

2. The WebSocket Connection Lifecycle

1// Step 1: Establish connection (ws:// for unencrypted, wss:// for TLS encrypted)
2const socket = new WebSocket('wss://echo.websocket.org');
3 
4// Step 2: Connection Opened
5socket.addEventListener('open', (event) => {
6 console.log('[WebSocket] Connection established!');
7 // Send data (strings or binary Blobs / ArrayBuffers)
8 socket.send(JSON.stringify({ type: 'LOGIN', userId: 'USR-101' }));
9});
10 
11// Step 3: Listen for incoming messages from server
12socket.addEventListener('message', (event) => {
13 const message = JSON.parse(event.data);
14 console.log('[WebSocket] Message received from server:', message);
15});
16 
17// Step 4: Handle errors
18socket.addEventListener('error', (err) => {
19 console.error('[WebSocket] Socket encountered error:', err);
20});
21 
22// Step 5: Connection closed
23socket.addEventListener('close', (event) => {
24 console.log(`[WebSocket] Closed: code=${event.code}, reason=${event.reason}`);
25});

3. Production Resilient WebSocket Client (Heartbeats & Auto-Reconnect)

Real-world mobile networks drop connections frequently. A production WebSocket wrapper implements exponential backoff reconnection and heartbeat ping/pongs:

1class ResilientWebSocket {
2 constructor(url) {
3 this.url = url;
4 this.reconnectAttempts = 0;
5 this.maxReconnectDelay = 30000;
6 this.heartbeatTimer = null;
7 this.connect();
8 }
9 
10 connect() {
11 this.ws = new WebSocket(this.url);
12 
13 this.ws.onopen = () => {
14 console.log('Connected. Resetting backoff.');
15 this.reconnectAttempts = 0;
16 this.startHeartbeat();
17 };
18 
19 this.ws.onmessage = (e) => {
20 if (e.data === '__PONG__') return; // Heartbeat response
21 console.log('Received payload:', e.data);
22 };
23 
24 this.ws.onclose = () => {
25 this.stopHeartbeat();
26 this.reconnect();
27 };
28 }
29 
30 startHeartbeat() {
31 this.heartbeatTimer = setInterval(() => {
32 if (this.ws.readyState === WebSocket.OPEN) {
33 this.ws.send('__PING__');
34 }
35 }, 15000);
36 }
37 
38 stopHeartbeat() {
39 clearInterval(this.heartbeatTimer);
40 }
41 
42 reconnect() {
43 const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), this.maxReconnectDelay);
44 console.log(`Connection lost. Reconnecting in ${delay}ms...`);
45 setTimeout(() => {
46 this.reconnectAttempts++;
47 this.connect();
48 }, delay);
49 }
50 
51 send(data) {
52 if (this.ws && this.ws.readyState === WebSocket.OPEN) {
53 this.ws.send(typeof data === 'string' ? data : JSON.stringify(data));
54 }
55 }
56}

4. Binary Data Over WebSockets

WebSockets can transmit binary data (Blob or ArrayBuffer) without base64 overhead:

1socket.binaryType = 'arraybuffer'; // Or 'blob'
2 
3socket.addEventListener('message', (e) => {
4 if (e.data instanceof ArrayBuffer) {
5 const view = new DataView(e.data);
6 console.log('Binary frame byte length:', view.byteLength);
7 }
8});

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What protocol scheme is used for secure, TLS-encrypted WebSocket connections?
Question 2
What is the primary performance advantage of WebSockets over HTTP long-polling?
Question 3
What property indicates whether a WebSocket is currently open and ready to transmit data?
Question 4
Why is an exponential backoff strategy essential for WebSocket reconnection logic?
Question 5
What binary data types can be sent directly over a WebSocket without string serialization?
Next Lesson

Server-Sent Events (SSE)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Symbols & Well-Known SymbolsServer-Sent Events (SSE)

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext