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.
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)