AI Computer Institute
Expert-curated CS & AI curriculum aligned to CBSE standards. A bharath.ai initiative. About Us

WebSockets: Real-Time Communication

📚 Web Development⏱️ 20 min read🎓 Grade 11
✍️ AI Computer Institute Editorial Team Updated: August 2026 CBSE-aligned · Peer-reviewed · 20 min read
Content curated by subject matter experts with IIT/NIT backgrounds. All chapters are fact-checked against official CBSE/NCERT syllabi.

The Problem: Refresh, Refresh, Refresh

Imagine you booked a waitlisted train ticket on IRCTC and you are desperate to know if your seat has been confirmed. What do most people do? They open the PNR status page, look at the result, close it, wait a few minutes, and open it again. And again. And again. You are doing all the work of asking, and the website only ever answers when you personally ask the question. If your seat gets confirmed the moment after you check, you will not find out until the next time you happen to refresh.

Now compare that to watching a live cricket score during a close match. The numbers on the screen change by themselves — a boundary is scored, and the total jumps from 182 to 186 without you touching anything. Nobody is refreshing a page. The screen seems to "know" the moment something happens.

Those two experiences use fundamentally different ways of talking to a server over the internet. The PNR page uses the web's normal method, which we will call request-response. The live score uses a different, older-than-you-think technology called a WebSocket. This chapter is about understanding exactly how a WebSocket lets a server "tap you on the shoulder" the instant something changes, instead of you having to keep asking.

How the Web Normally Talks: Request and Response

Every time your browser loads a normal web page, it follows a strict pattern defined by a protocol called HTTP (HyperText Transfer Protocol):

  1. Your browser sends a request to a server: "Please give me this page" or "Please give me the current PNR status for ticket X."
  2. The server processes that request and sends back a response: the HTML of the page, or the current status.
  3. The connection's job is done. The server does not keep talking to you after that. It has answered your one question and moved on to serve other people.

This is called a half-duplex, request-driven pattern: the server can only ever speak when spoken to. It is a bit like sending a postcard to a friend asking "any news?" — your friend can only reply once they receive your postcard, and they can never write to you first just because something happened on their end. If they have exciting news five minutes after your postcard arrives, they must simply wait for your next postcard before they can tell you.

For most of the web — reading a news article, searching Google, opening your school's result portal — this is perfectly fine, because you are the one deciding when you want new information. But it breaks down badly for anything that changes on its own, faster than you can keep asking.

The Postcard Problem: Why Polling Keeps Asking Anyway

To work around this limitation, early real-time-ish websites used a technique called polling: the browser automatically re-sends a request every few seconds, just in case something changed. It is exactly like posting a fresh postcard every three seconds, forever, whether or not there is actually any news.

Let's work out how wasteful this really is with real arithmetic. Suppose an app polls a server every 3 seconds to check for cricket score updates, and you leave it open for 10 minutes while watching an over-by-over passage of play where the score genuinely changes only twice (say, a boundary and a wicket).

  • 10 minutes = 600 seconds.
  • Polling every 3 seconds means 600 ÷ 3 = 200 separate request-response exchanges.
  • Every one of those 200 exchanges carries a full set of HTTP headers — the web address, cookies, the browser's identity string, what content types it accepts, and more. Even a "nothing changed" reply typically costs several hundred bytes of overhead. Taking a round, typical figure of about 600 bytes per exchange, that is roughly 200 × 600 = 120,000 bytes, or about 117 KB, sent back and forth — almost entirely to say "no news yet."
  • Out of those 200 exchanges, only 2 actually carried anything useful.

That is the postcard problem in numbers: 198 out of 200 postcards said nothing new, but you still had to write, post, and receive every single one of them. And worse — if the poll interval is 3 seconds but a wicket falls 1 second after your last check, you still find out up to 2 seconds late. Polling trades data and battery for a rough approximation of "real time," and it is never actually instant.

A Phone Call Instead of Postcards: Meet WebSockets

A WebSocket solves this by changing the shape of the conversation entirely. Instead of exchanging postcards over and over, imagine you called your friend on the phone and simply stayed on the line. Now your friend can speak the instant they have news — they don't wait for you to ask, and you don't have to keep dialling. Either of you can talk whenever you want, in either direction, over the one connection that stays open.

Formally: a WebSocket is a communication protocol that establishes a single, persistent, full-duplex connection between a browser (or app) and a server over TCP. "Persistent" means the connection stays open for as long as both sides want it to, instead of closing after one exchange. "Full-duplex" means both sides can send messages independently at any time — the server does not need to wait for a request before it pushes data to you.

This is the exact mechanism behind a live cricket score updating itself, a chat message appearing the instant it's sent, or a multiplayer quiz app showing everyone's answer live. The server simply sends a message down the already-open connection the moment something happens — no postcard needed.

How the Connection Actually Opens: The Handshake

Here is something students often get wrong: a WebSocket connection does not appear out of nowhere. It is born from an ordinary HTTP request that politely asks to be upgraded. This matters because it lets WebSockets travel through the same networks, firewalls, and ports that already understand normal web traffic.

The browser sends a special HTTP request like this:

GET /live HTTP/1.1
Host: score.example.in
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

Notice the Upgrade: websocket line — the browser is saying "I would like to switch this connection from plain HTTP to the WebSocket protocol." The Sec-WebSocket-Key is a random value generated just for this request. If the server understands WebSockets, it replies not with a normal page, but with:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

Status code 101 means "Switching Protocols" — the server is agreeing to stop speaking plain HTTP and start speaking WebSocket instead, on this same connection. The Sec-WebSocket-Accept value is not random: the server takes the key you sent, joins it with a fixed constant string that only real WebSocket servers know, runs it through a hashing function, and encodes the result. This proves the reply is coming from a server that genuinely understands the WebSocket protocol, rather than some ordinary HTTP server accidentally echoing your request back.

Once this handshake succeeds, the "phone call" has begun. No more HTTP requests and responses are exchanged — instead, both sides send lightweight frames (small packaged messages) directly over the same TCP connection, in either direction, whenever they want.

Seeing the Difference

The diagram below lines up both approaches side by side over the same stretch of time. On the left, the browser has to keep asking, and most answers are empty. On the right, one handshake is enough, and the server pushes news the moment it happens.

Polling: keep asking WebSocket: open line, pushed anytime Browser Server no update wicket! no update no update boundary! 200 exchanges in 10 min, only 2 carried real news Browser Server handshake (101) open connection push: wicket! push: boundary! "unsubscribe" (client speaks anytime too) 1 handshake + only the messages that matter, either direction

Talking to a WebSocket from Code

In JavaScript, opening a WebSocket takes a single line, because the browser handles the handshake for you automatically:

const socket = new WebSocket("wss://score.example.in/live");

socket.onopen = () => {
  console.log("Connected! Waiting for match updates...");
};

socket.onmessage = (event) => {
  const update = JSON.parse(event.data);
  console.log(`${update.team}: ${update.runs}/${update.wickets} in ${update.overs} overs`);
};

socket.onclose = () => {
  console.log("Connection closed.");
};

socket.onerror = (error) => {
  console.log("Something went wrong:", error);
};

Let's trace this exactly as the browser would run it:

  1. new WebSocket(...) immediately starts the HTTP-upgrade handshake described earlier, in the background. The code does not pause and wait — it moves on to set up the event handlers below.
  2. The moment the server replies with status 101 and the handshake finishes, the browser fires the open event, so "Connected! Waiting for match updates..." is printed.
  3. Sometime later, with no new request from the browser at all, the server decides a wicket has fallen and pushes a message down the still-open connection. This fires onmessage. Suppose event.data arrives as the text {"team":"India","runs":187,"wickets":4,"overs":"32.3"}.
  4. JSON.parse(event.data) converts that text into a real JavaScript object: update.team is "India", update.runs is 187, update.wickets is 4, update.overs is "32.3".
  5. The template literal then prints exactly: India: 187/4 in 32.3 overs.
  6. This repeats — with no new connection, no new handshake, no new headers — every single time the server has something new to say, for as long as the connection stays open.

A WebSocket connection is not one-way. The browser can talk back over the same open line using socket.send(...), for example socket.send(JSON.stringify({ type: "subscribe", match: "IND_vs_AUS" })) to tell the server which match it cares about. This is what "full-duplex" means in practice: sending and receiving are completely independent of each other.

What Happens on the Server Side

The server needs to accept the upgraded connection and keep track of every client currently connected, so it knows who to push updates to. A simplified version, using a popular WebSocket library for Node.js called ws, looks like this:

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

server.on("connection", (clientSocket) => {
  console.log("A new client joined");

  clientSocket.send(JSON.stringify({
    team: "India", runs: 187, wickets: 4, overs: "32.3"
  }));

  clientSocket.on("message", (msg) => {
    console.log("Client says:", msg);
  });
});

Here, server.on("connection", ...) runs once for every browser that successfully completes a handshake, handing back a clientSocket object that represents that one open line. The server can call .send() on it at any moment — it does not need the client to have asked anything first. When a real match score-tracking service detects that the score changed (perhaps by watching an official data feed), it loops through every connected clientSocket and sends the update to each one. That is the entire mechanism behind "the number just updates on its own."

Worked Example: A Live Score Tracker, Start to Finish

Let's put the whole lifecycle together as a single trace, the way you would need to describe it in a CBSE exam answer:

  1. Handshake: Your browser sends an HTTP request with Upgrade: websocket to the score server. The server checks the Sec-WebSocket-Key, computes the matching Sec-WebSocket-Accept, and replies with status 101. The connection is now a WebSocket, not plain HTTP.
  2. Subscribe: Your browser sends one small message: {"type":"subscribe","match":"IND_vs_AUS"}. The server notes that this particular connection wants updates for that match.
  3. Silence, correctly: For the next 47 seconds, nothing is sent at all in either direction, because nothing has changed. Unlike polling, no wasted requests are sent during this silence — the connection simply stays open and idle.
  4. Push: A wicket falls. The server immediately sends {"team":"India","runs":187,"wickets":4,"overs":"32.3"} to every subscribed connection, including yours, without being asked.
  5. Client reacts: Your onmessage handler fires, parses the JSON, and updates the number on your screen — typically within a fraction of a second of the real event.
  6. Close: When you leave the page, the browser sends a close frame, the server removes your connection from its list of subscribers, and both sides free up the resources they were using.

Compare that to arithmetic from earlier: a polling approach checking every 3 seconds for the same 10-minute period made 200 request-response round trips carrying roughly 120,000 bytes total, to deliver 2 pieces of real news, each up to 3 seconds late. The WebSocket approach made 1 handshake (a few hundred bytes) plus exactly as many push messages as there were real events — 2 messages of perhaps 60 bytes each, arriving within a fraction of a second of the actual event. Even accounting for the handshake, the WebSocket approach is off by roughly two orders of magnitude in data sent, and it is faster to boot. This is precisely why every genuinely real-time feature on the modern web — live scores, live chat, live multiplayer games, live collaborative documents — is built on WebSockets rather than polling.

Two Misconceptions Worth Correcting

Misconception 1: "A WebSocket is just a faster kind of HTTP request." This is wrong in an important way. HTTP and WebSocket are different protocols. A WebSocket connection is born from a single HTTP request (the handshake), but the moment the server replies with status 101, the two sides stop speaking HTTP altogether and switch to WebSocket's own lightweight message-framing format for as long as the connection lives. There is no repeated request-response cycle hiding underneath — the connection itself stays open, which is precisely why it avoids the header overhead we calculated above.

Misconception 2: "Socket" in "WebSocket" means the same thing as the sockets used in general computer networking. Not quite. In networking generally, a "socket" is any endpoint of a two-way TCP or UDP connection between two machines, identified by an IP address and port number — a very old, general-purpose idea used by everything from email servers to online games. A WebSocket is a specific protocol, standardized for the web in 2011 as RFC 6455, that runs its messages on top of one such ordinary TCP socket, but adds its own handshake (so it can pass through the same firewalls and proxies that expect HTTP) and its own message framing (so browsers and servers agree on where one message ends and the next begins). Every WebSocket connection uses a TCP socket underneath, but not every TCP socket is a WebSocket.

ws:// and wss://, and Where This Fits for Your Exams

WebSocket URLs use their own scheme names instead of http or https: a plain WebSocket address starts with ws://, and an encrypted one — running over TLS, exactly the way https:// encrypts ordinary web traffic — starts with wss://. Any real application handling sensitive data (bank balances, personal chat, exam results) must use wss://, never ws://, for the same reason your bank's website must use https:// and never plain http://.

For CBSE Computer Science / Informatics Practices, you should be able to: (1) define a WebSocket as a persistent, full-duplex connection between client and server, distinct from HTTP's request-response model; (2) explain why polling is inefficient using a worked numeric comparison like the one above; (3) name at least two real applications that require real-time, server-initiated updates (a live score feed and a chat application are safe, accurate examples); and (4) recognise that a WebSocket connection begins life as an HTTP request that is "upgraded," rather than existing as a wholly separate kind of network request from the start.

Check Your Understanding

  1. A weather app checks a server every 10 seconds for 5 minutes, even though the temperature only changes once in that time. How many request-response exchanges does it make, and how many of them carry real news?
  2. What HTTP status code signals that a WebSocket handshake succeeded, and what does that status code's name mean?
  3. Why can the server send you a cricket-score update without you having asked for one, once a WebSocket connection is open — but not when you are only using plain HTTP?
  4. A classmate says, "wss:// is just a WebSocket that loads faster." What is wrong with that statement, and what does the "s" actually add?

Answers: (1) 5 minutes = 300 seconds, so 300 ÷ 10 = 30 exchanges; only 1 of those carries the actual temperature change. (2) Status 101, "Switching Protocols" — it means the server has agreed to stop speaking HTTP and start speaking WebSocket over the same connection. (3) Because the WebSocket connection is full-duplex and stays open indefinitely, so the server can write to it at any moment; plain HTTP closes the exchange after each response and the server has no open channel to write into until the browser asks again. (4) It is wrong because "s" stands for TLS encryption (security), the same as in https://, not speed — a wss:// connection is not inherently faster than a ws:// one, it is protected from eavesdropping.

Summary

Plain HTTP is a request-response protocol: the server can only speak when the browser asks a question, which is why apps that need constant updates historically resorted to polling — repeatedly re-asking on a timer, wasting bandwidth and still arriving late. A WebSocket connection is established through a one-time HTTP handshake (request with Upgrade: websocket, response with status 101) and then becomes a persistent, full-duplex channel over a single TCP connection, letting either side send a message the instant it has something to say, with only a few bytes of framing overhead per message instead of a full set of HTTP headers. This is the real mechanism behind live cricket scores, chat apps, and any other feature where numbers or messages appear to update themselves — and it works because the server, not just the browser, is finally allowed to speak first.

← Building a Blog with Flask and SQLAlchemyGenerators and Iterators: Memory-Efficient Processing →

Found this useful? Share it!

📱 WhatsApp 🐦 Twitter 💼 LinkedIn