WebSockets is a communication protocol that enables full-duplex, persistent connections between a client (like a web browser) and a server over a single TCP connection.
Here’s a breakdown:
- Traditional HTTP is request-response based: the client sends a request, and the server responds, then the connection usually closes.
- WebSockets, on the other hand, keep the connection open, allowing both client and server to send messages to each other at any time without re-establishing connections.
Key Features of WebSockets
- Full-duplex: Both client and server can send messages independently.
- Persistent connection: After the initial handshake over HTTP(S), the connection remains open.
- Lower overhead: No need to repeatedly send HTTP headers for every message.
- Real-time communication: Ideal for chat apps, live dashboards, multiplayer games, and stock tickers.
How It Works
- Handshake: The client makes an HTTP request asking to upgrade the connection to WebSocket.
- Upgrade: The server accepts and upgrades the protocol.
- Persistent channel: Both sides can now push data instantly.
Example (JavaScript)
// Client-side
const socket = new WebSocket("ws://example.com/socket");
// When connected
socket.onopen = () => {
console.log("Connected!");
socket.send("Hello Server!");
};
// Receiving messages
socket.onmessage = (event) => {
console.log("Message from server:", event.data);
};
Common Uses
- Chat and messaging apps
- Online multiplayer games
- Live notifications (social media, sports scores)
- Collaborative tools (Google Docs-like editing)
- Financial trading platforms (live stock/crypto prices)