What Is WebSocket? How It Works and What It Is For

WebSocket keeps a single connection open and bidirectional between client and server. What it is, how the HTTP handshake works and where it is used in real time.

Pasillo de un centro de datos con bastidores de servidores iluminados en azul y una línea naranja que recorre el suelo hacia una puerta al fondo

WebSocket keeps one connection open and lets both ends of it talk at once. No more browser asking «anything new?» every second. The client and the server hold the line, and either one sends data the moment it has something to say. That is the machinery under live chat, multiplayer games and the dashboards that refresh themselves in front of you.

Here is the deal. Below you will find how the connection opens by borrowing HTTP, what «full-duplex» really means, how it differs from polling and SSE, where it gets used and how to secure it. Keep two primary sources within reach: the IETF’s RFC 6455 and MDN’s documentation.

What is WebSocket?

A WebSocket is an application-layer protocol that hands the web something HTTP never gave it out of the box: a connection that stays open while messages travel in both directions. Take the classic socket, the endpoint through which one program connects to another. WebSocket carries that idea into the browser on the ports the web already opens.

It does not replace HTTP. It leans on HTTP to get in the door. The connection begins life as an ordinary HTTP request, asks for a protocol switch and from that point speaks its own format. Underneath, TCP still does the heavy lifting, the same reliable transport that carries the web and your email, so everything you know about the layers of TCP/IP keeps applying.

The IETF standardised it as RFC 6455, published in December 2011, right in the middle of the HTML5 wave. JavaScript’s WebSocket object, the part you actually touch, comes from the WHATWG’s living HTML standard. Two URL schemes tell you the whole story:

  • ws://: unencrypted WebSocket, port 80 by default (like HTTP).
  • wss://: WebSocket over TLS, port 443 by default (like HTTPS).

The JavaScript API stays deliberately small. You create the connection with new WebSocket(url), listen for the open, message and close events, and send with send(). That object is never the hard part. Reconnection, authentication and the meaning of your messages are.

How the connection is established: the HTTP handshake

The cleverest piece of the design is the door it uses. WebSocket walks in through the same entrance as everything else, an HTTP request. Your client fires a GET with three headers that matter. Upgrade: websocket pops the question, Sec-WebSocket-Key carries a random value that keeps a cached response from being replayed, and Sec-WebSocket-Version: 13 pins the protocol version:

GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

If the server accepts, you do not get a 200. You get a 101 Switching Protocols plus a Sec-WebSocket-Accept that the server calculates from your key. The client runs the same arithmetic and checks it matches. If it does not, it hangs up. From that 101 onward the connection stops being HTTP and the messages travel as protocol frames. When the server has no idea what WebSocket is, it answers with an ordinary HTTP response and nothing breaks. You simply stay on a regular web page. That coexistence is exactly what lets the protocol cross servers, proxies and firewalls that have never heard of it.

The handshake is also where both sides agree on the extras. Sec-WebSocket-Protocol negotiates a subprotocol, a name such as mqtt or graphql-ws that tells both ends which higher-level language they will speak on top. Sec-WebSocket-Extensions picks extensions such as compression. Both are optional, and a bare WebSocket with no subprotocol is perfectly valid.

Inside the channel, every message rides in one or more frames, each with an opcode that says what it is: text, binary, continuation, close, ping or pong. The standard demands that client frames be masked, obfuscated with a random key, so they cannot poison intermediate caches. Server frames go unmasked. Because a proxy may drop a connection that sits idle, the protocol ships ping/pong messages that applications use as a heartbeat. To shut down cleanly there is a close handshake with a status code, and the one you will see most is 1000.

Full-duplex: what it means

Call WebSocket full-duplex and you are saying both ends can send and receive at the same time, with no taking turns. A classic HTTP exchange is rigid. One side asks, the other answers, and nothing new goes out until the reply comes back. That is half-duplex. WebSocket breaks the turn-taking. The server pushes data the instant it has it, without being asked, and the client can do the same in parallel. That is where real time comes from.

Stay honest about the caveat. Full-duplex describes the channel, not the speed. WebSocket will not fix a slow network. Round-trip latency is still there, and in real time it matters as much as bandwidth. If the link drags, measure and improve your internet speed before you blame the protocol.

WebSocket vs polling, long polling and SSE

Before WebSocket, real time was faked on top of HTTP. Polling asks every so often whether there is news. Simple, and wasteful, because almost every request comes back empty. Long polling leaves the request open until there is something to send or a timeout expires. That cuts the waste and holds connections open in exchange. SSE (Server-Sent Events) is a one-way channel from server to client over a text/event-stream the browser manages with EventSource, and it reconnects on its own. WebSocket is the only one of the four that is genuinely bidirectional.

Polling Long polling SSE WebSocket
Direction Client to server Client to server Server to client Bidirectional
Transport HTTP HTTP HTTP TCP (after the upgrade)
Latency High (depends on the interval) Medium Low Low
Overhead High: headers on every round Medium Low Minimal per message
Reconnection The client does it The client does it Automatic The application schedules it
Typical use Data that rarely changes Legacy chat, alerts Notifications, feeds Chat, games, real time

The practical rule is short. If only the server has something to say, SSE is usually enough and it is simpler. If you need both directions and latency matters, go with WebSocket. If the data changes once in a blue moon, plain polling still holds up. The known limits of long polling and of streaming over HTTP are collected in RFC 6202.

An example makes the trade-off concrete. Picture a trading dashboard showing prices for a thousand instruments. Polling every second fires a thousand requests a minute from each client, and almost all of them come back with the same number. Long polling keeps a thousand connections open doing nothing. SSE needs one stream per client because the updates only travel one way. Now let the user place an order over that same channel and the balance tips. WebSocket carries the price stream and the commands.

What WebSocket is used for

It shows up wherever information has to arrive without anyone asking for it.

  • Chat and messaging. The textbook example. A message has to appear instantly on someone else’s screen, along with the «typing…» indicator or the read receipts.
  • Multiplayer games. Every player needs to see and send moves with as little delay as possible, so a persistent channel spares you the request dance.
  • Live data. Stock quotes, sports scores, sensor telemetry or metrics that refresh themselves on a dashboard.
  • Collaborative editing. Several people touching the same document at once sync their changes continuously in both directions.
  • WebRTC signalling. Before a video call has audio and video, the parties swap connection details, and WebSocket is a common channel for that.

All five share the same shape: a steady stream of small updates that has to reach the other side right now, not on the next refresh.

Security: WSS and good practice

A WebSocket is a door left open, so it pays to know who walks through it. The first move is to use WSS every time. Nobody serves a login over plain HTTP today, and shipping data over an exposed ws:// makes no more sense. wss:// runs over TLS, its current version is TLS 1.3 in RFC 8446, and it encrypts the whole channel, credentials included. Encryption does not solve everything. These are the precautions that make the difference, in line with OWASP’s guide:

  • Check the origin. The browser sends the Origin header during the handshake, and validating it stops a third-party site from opening a connection in your user’s name (cross-site WebSocket hijacking). Ordinary CORS does not cover this case.
  • Authenticate after connecting and on every message. The channel stays alive for a long time, so verify identity and permissions for each action, not only when it is opened.
  • Distrust what arrives. A WebSocket message is user input. Validate it, cap its size and check its format.
  • Set limits and keep secrets out of the URL. Maximum message size, connection count and timeouts. Tokens belong in authentication, not on display in the address.

No protocol is insecure by itself. What fails is almost always the configuration. The same old slips come back: validating too little, trusting the wrong origin and forgetting permissions. The article on what a hacker is and the types that exist helps you step into the shoes of whoever is hunting for the gap.

The current state of WebSocket

The protocol has run more than a decade without changes to its core, and that is a good sign. RFC 6455 is still the standard, version 13 is what gets negotiated and browser support has been universal for years. HTTP/2 and HTTP/3, the latter defined in RFC 9114, brought important improvements. Neither one has dethroned WebSocket, because they solve different problems.

Progress happens around it. Extensions such as permessage-deflate, described in RFC 7692, compress the messages. WebTransport, a newer API aimed at HTTP/3, brings streams and datagrams with very low latency, and it covers cases where WebSocket falls short. It joins the toolbox alongside the older tool.

Conclusion

WebSocket turned the web into a real-time medium with one simple idea. Start as an HTTP request, ask for a protocol switch with a handshake, and after the 101 hold a persistent, bidirectional channel where both ends speak whenever they want. Chat, games and live dashboards sit on that base.

So run the decision before you write a line of code. Both directions and low latency? WebSocket, always over wss://, with origin validation and permissions in place. Server to client only? SSE saves you work and code. The four pieces that matter are the handshake, the full-duplex channel, how it compares with the alternatives and how you secure it. Read RFC 6455 once. The handshake section is shorter than you expect, and it will save you a week of guessing.

Frequently asked questions

Does WebSocket replace HTTP?

No, it complements it. The connection starts as an HTTP request that asks for a protocol switch and, after the 101, stops being HTTP. HTTP still serves pages and APIs, and WebSocket only handles the part that needs to travel in real time and in both directions.

What is the difference between WebSocket and a normal socket?

A socket is the general idea of an endpoint between two programs, at a lower level. WebSocket is a concrete protocol for the web that leans on HTTP to open and then defines its own frames. Every WebSocket uses sockets, and plenty of socket uses have nothing to do with WebSocket.

What port does WebSocket use?

The same ones HTTP does: 80 for ws:// and 443 for wss://. It is one of its advantages, since those ports are open on almost any network. You can change them, but you rarely need to.

Why does my WebSocket connection keep dropping?

Almost always because of something idle in between. Proxies, load balancers and firewalls close connections that go too long without traffic. The standard fix is the ping/pong heartbeat and, above all, an application that knows how to reconnect on its own. A WebSocket connection is not forever, so assume it will drop and plan for it.