What is WebSocket?
Normally, web communication works via HTTP. A client sends a request, the server responds, and the connection ends.
But what if you need real-time updates — like in chat apps, online games, or stock tickers?
Opening a new HTTP request for every update would be too slow and heavy.
That’s where WebSocket comes in.
Key Idea
- WebSocket creates a persistent, two-way connection between client and server.
- Instead of “ask and reply”, both sides can send messages anytime.
- It starts as an HTTP request, then “upgrades” the connection to WebSocket.
Why WebSocket?
- Real-time communication (chats, notifications, multiplayer games).
- Efficiency — no need to reopen connections all the time.
- Bi-directional — both client and server can send data.
Example in JavaScript
// Client-side WebSocket
const socket = new WebSocket("ws://localhost:8080");
// When connection opens
socket.onopen = () => {
console.log("Connected to server");
socket.send("Hello Server!");
};
// When message is received
socket.onmessage = (event) => {
console.log("Message from server:", event.data);
};
On the server side (Node.js example with ws):
const WebSocket = require("ws");
const server = new WebSocket.Server({ port: 8080 });
server.on("connection", (socket) => {
console.log("Client connected");
socket.on("message", (msg) => {
console.log("Received:", msg);
socket.send("Echo: " + msg);
});
});
Summary
- WebSocket = always-open, two-way connection between client and server.
- Perfect for real-time apps.
- Starts as HTTP, upgrades to WebSocket.
- Simpler and faster than polling for frequent updates.