WebSockets are a communication technology that enables continuous, two-way data exchange between a client and a server over a single persistent connection.
Unlike traditional HTTP communication, where clients usually initiate individual requests, WebSockets allow both sides to send messages whenever needed.
They are commonly used for chat applications, live dashboards, online games, notifications, and real-time data feeds.
A WebSocket connection typically begins with an HTTP request and then switches to the WebSocket protocol.
The process includes:
This reduces the need to repeatedly establish new HTTP connections.
WebSockets and HTTP are designed for different communication patterns.
| Feature | WebSockets | Traditional HTTP |
|---|---|---|
| Connection | Persistent | Usually request-response |
| Communication | Bidirectional | Primarily client initiated |
| Real-time updates | Well suited | Often requires polling or streaming |
| Overhead | Low after connection setup | Headers sent with repeated requests |
HTTP remains ideal for standard webpage and API requests, while WebSockets are useful when frequent real-time communication is required.
Both can deliver timely updates, but they work differently.
WebSockets are better suited to continuous communication, while webhooks work well for event notifications between servers.
Some websites use WebSockets to deliver information that changes continuously, such as prices, scores, or live notifications.
A data collection application may need to connect to a permitted WebSocket endpoint rather than repeatedly requesting the webpage.
Unlike ordinary HTML scraping, this requires processing a stream of messages and understanding the application's message format.
A browser can create a WebSocket connection using JavaScript:
const socket = new WebSocket("wss://example.com/socket");
socket.addEventListener("open", () => {
console.log("Connected");
});
socket.addEventListener("message", event => {
console.log("Received:", event.data);
});
socket.addEventListener("close", () => {
console.log("Disconnected");
});
The wss scheme represents a WebSocket connection protected with TLS.
Once connected, the server can send new information without waiting for the browser to make another HTTP request.
WebSockets provide persistent, bidirectional communication between clients and servers.
They are ideal for applications requiring frequent real-time updates, including chat, live dashboards, games, and streaming data. Their main trade-offs are connection management, scaling complexity, and the need to handle interruptions reliably.