WebSocket
In short
WebSocket is a protocol that keeps a single connection open between a browser and a server so both sides can send each other messages instantly at any time.
What is WebSocket?
With plain HTTP, the client always has to ask first and the server can only answer. WebSocket removes that limit: after one initial HTTP request that asks to upgrade the connection, the browser and server keep a persistent, two-way channel open and can each send messages whenever they want, with very little overhead per message.
In the browser, the WebSocket API opens a connection to a ws:// or, preferably, an encrypted wss:// URL, and your code listens for open, message, and close events. Typical uses include chat apps, multiplayer games, live dashboards, collaborative editors, trading screens, and notifications, anywhere updates need to arrive in real time.
HTTP is like sending letters, where every reply needs a new request, while WebSocket is like a phone call that stays open so either side can speak at any moment. The trade-off is that servers must hold many long-lived connections, which affects scaling, load balancing, and the reconnect logic needed when networks drop.
WebSocket is often compared with polling and Server-Sent Events (SSE). Polling repeatedly asks the server for news, which is simple but wasteful, while SSE streams updates from server to client only, which is enough for live feeds and many AI chat responses. For security, always use wss://, authenticate the connection, check the Origin header during the handshake, and validate every incoming message like any other untrusted input.
At a glance
Key takeaways
- WebSocket provides a persistent, two-way connection between client and server.
- It starts as an HTTP request that is upgraded to the WebSocket protocol.
- Either side can send messages at any time with low overhead.
- It suits chat, games, live dashboards, and collaboration tools.
- Use
wss://, authenticate connections, and validate every message.
Example
// Open an encrypted WebSocket connection
const socket = new WebSocket("wss://chat.example.com/rooms/42");
// Send a message once the connection is ready
socket.addEventListener("open", () => {
socket.send(JSON.stringify({ type: "join", user: "ada" }));
});
// The server can push messages at any time, without a new request
socket.addEventListener("message", (event) => {
const message = JSON.parse(event.data);
console.log(`${message.user}: ${message.text}`);
});Readers ask
What is the difference between WebSocket and HTTP?
HTTP follows a request-response pattern where the client must ask before the server can reply. WebSocket starts with an HTTP handshake, then keeps the connection open so both sides can send messages at any time.
When should I use WebSocket instead of Server-Sent Events?
Use WebSocket when both the client and the server need to send frequent messages, as in chat or multiplayer games. Server-Sent Events are simpler and run over regular HTTP when updates only flow from the server to the client.
Often compared
See also
- HTTPWeb Development, p. 19HTTP is the protocol that browsers, apps, and servers use to exchange web pages and data through a simple cycle of requests and responses.
- JavaScriptWeb Development, p. 24JavaScript is the programming language that runs in web browsers to make pages interactive, and it also runs on servers through runtimes like Node.js.
- APIBackend & APIs, p. 2An API is a set of rules that lets one piece of software request data or actions from another in a predictable, documented way.
- TLSSecurity, p. 45TLS is the cryptographic protocol that encrypts data sent over a network and verifies the server's identity, securing HTTPS, email, and many other connections.
- Load BalancerDevOps & Cloud, p. 34A load balancer is a server or service that spreads incoming traffic across several backend servers so no single one is overloaded and the app stays available.
- Event-Driven ArchitectureSoftware Architecture, p. 18Event-driven architecture is a software design style in which services communicate by producing and reacting to events, such as an order being placed.
Sources
Spotted a mistake or something missing on this page?Suggest an edit