WebSockets
In short: WebSockets are a persistent, bidirectional connection between browser and server over which both sides can send messages at any time.
In more detail: Normal HTTP works as question and answer: the browser asks, the server answers, then it is over. For chats, live games, stock prices or shared editing that is too sluggish. A WebSocket stays open, and the server can send on its own (“push”).
In Depth
- Set-up: the browser starts with a normal HTTP request and asks for an “upgrade”. Afterwards the connection continues as a WebSocket (address
ws://or encryptedwss://, see TLS). - Advantages: very low latency, little overhead per message, real time in both directions.
- Disadvantages: the open connection occupies server resources (scaling is harder). If it drops, the client must reconnect.
- Alternatives: polling (asking again and again), server-sent events (server → client only) and services that wrap WebSockets.
- Security: check the origin (
Origin), authenticate users, validate messages like any input, usewss://.