Skip to content

What Is a WebSocket? Full-Duplex Communication Over a Single Connection

Sep 21, 2026 · Web Development

A WebSocket is a communication protocol that keeps a single, persistent TCP connection open between a client and a server so both sides can send messages to each other at any time. Unlike the request-response model of HTTP, a WebSocket connection stays alive after an initial handshake, giving you low-latency, full-duplex communication. That makes it the natural choice for chat apps, live sports scores, trading dashboards, multiplayer games, and collaborative editors where the server must push data the instant it changes rather than waiting to be asked.

Key takeaways

  • WebSockets provide full-duplex (two-way) messaging over one long-lived TCP connection.
  • The connection starts as an HTTP request that is upgraded using the Upgrade: websocket header.
  • Use ws:// for plaintext and wss:// for TLS-encrypted traffic; prefer wss:// in production.
  • They remove the overhead of repeatedly opening connections and re-sending headers the way polling does.
  • They are ideal for real-time server push but overkill for simple, occasional request-response calls.
  • Because connections are stateful, scaling needs sticky sessions or a shared pub/sub backend.

How does a WebSocket connection work?

A WebSocket connection has two phases: the handshake and the data transfer. The handshake is a standard HTTP GET request that asks the server to switch protocols. The client sends headers such as Upgrade: websocket, Connection: Upgrade, and a random Sec-WebSocket-Key.

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

If the server supports WebSockets, it replies with status 101 Switching Protocols and a computed Sec-WebSocket-Accept value derived from the client key. That computed value proves the server understood the WebSocket handshake rather than blindly echoing data, which protects against certain cache-poisoning tricks. From that moment the same TCP socket stops speaking HTTP and starts exchanging WebSocket frames.

Each frame carries a small header plus a payload, so per-message overhead is tiny compared to a full HTTP request with all its headers. Data flows as discrete messages rather than a raw byte stream you must frame yourself. A message can be a text frame containing UTF-8 or a binary frame containing arbitrary bytes, and either side can send at any moment, which is exactly what full-duplex means. The protocol also defines control frames for closing the connection and for ping/pong keepalives.

How is a WebSocket different from HTTP?

HTTP is half-duplex and client-driven: the client asks, the server answers, and the connection is often closed or returned to a pool. To get new data the client must ask again. A WebSocket flips that model: after the upgrade, the server can send unprompted messages, and there is no per-message header cost.

  • Direction: HTTP is request-response; WebSockets are bidirectional.
  • Lifetime: HTTP connections are typically short-lived; WebSocket connections persist.
  • Overhead: Every HTTP request re-sends headers and cookies; WebSocket frames add only a few bytes.
  • Latency: WebSockets avoid repeated setup, so updates arrive with minimal delay.

It is worth noting that WebSockets are not a wholesale replacement for HTTP. Loading pages, fetching resources, and normal REST calls still belong to HTTP. WebSockets are a specialized tool for the real-time slice of an application.

When should you use WebSockets?

Reach for WebSockets when updates are frequent, must arrive quickly, and can originate on the server. If your data changes rarely or the client is fine asking on a schedule, a simpler approach is often easier to build and operate.

Technique Direction Best for Drawback
HTTP polling Client to server Infrequent updates, simple setup Wasted requests, higher latency
Server-Sent Events Server to client One-way live feeds, auto-reconnect No native client-to-server push
WebSocket Both ways Chat, games, live collaboration Stateful, harder to scale

Good fits include chat and messaging, live location tracking, collaborative documents, real-time feeds, and multiplayer game state. Poor fits include one-off form submissions and REST-style CRUD, where the extra complexity buys you nothing. If updates only flow from server to client, Server-Sent Events are often the simpler and more robust choice because they reconnect automatically and run over ordinary HTTP.

How do you open a WebSocket in JavaScript?

Browsers ship a built-in WebSocket object. You create it with a URL, then attach event handlers for open, message, error, and close.

const socket = new WebSocket("wss://example.com/chat");

socket.addEventListener("open", () => {
  socket.send(JSON.stringify({ type: "hello" }));
});

socket.addEventListener("message", (event) => {
  const data = JSON.parse(event.data);
  console.log("received", data);
});

socket.addEventListener("close", (event) => {
  console.log("closed", event.code, event.reason);
});

Note that send only works after the open event fires. A common beginner mistake is calling send immediately after construction, before the handshake completes, which throws an error. The close event exposes a numeric code and a reason string that help you distinguish a clean shutdown from an abnormal drop.

What is a WebSocket subprotocol, and how do libraries differ?

The raw WebSocket protocol only defines how to move opaque messages. It does not tell you what those messages mean, how to route them, or how to recover from a disconnect. Two mechanisms fill that gap.

First, WebSockets support subprotocols, an application-level agreement negotiated during the handshake through the Sec-WebSocket-Protocol header. The client offers one or more names, and the server picks one, so both sides know which message format to expect.

Second, libraries add conveniences the bare protocol lacks. Socket.IO, for example, layers on automatic reconnection, acknowledgements, rooms, and a fallback transport, at the cost of not being a plain WebSocket on the wire. Choosing between a thin client and a full library is a real design decision:

  • A thin WebSocket client is lightweight and standards-based but leaves reconnection, heartbeats, and message routing to you.
  • A batteries-included library handles those concerns but adds dependencies and a custom protocol that both ends must share.

What are common WebSocket pitfalls?

The stateful, long-lived nature of WebSockets creates a distinct set of traps.

  • No automatic reconnection. The browser WebSocket API does not reconnect after a drop. You must detect close and reconnect, ideally with exponential backoff and jitter to avoid thundering-herd reconnects.
  • Silent connection death. A connection can appear open while the underlying network is gone. Send periodic ping/pong or heartbeat messages and close connections that stop responding.
  • Unbounded send buffers. If the client cannot keep up, buffered data grows. Watch bufferedAmount and apply backpressure.
  • Assuming ordering across connections. Messages within one connection are ordered, but after a reconnect you may miss messages sent while disconnected. Add sequence numbers or a resume token.
  • Idle timeouts. Load balancers and proxies often close idle connections after a fixed period, which heartbeats also help prevent.

How do you secure WebSockets?

Security for WebSockets needs deliberate attention because the browser same-origin policy does not restrict them the way it restricts fetch.

  • Always use wss://. TLS encrypts the payload and helps the connection pass through proxies on port 443.
  • Validate the Origin header on the server. Browsers send it during the handshake; reject unexpected origins to defend against cross-site WebSocket hijacking.
  • Authenticate explicitly. Cookies are sent on the handshake, but relying on them alone is risky. Pass a short-lived token and verify it server-side before accepting the connection.
  • Authorize every message. Do not assume that an authenticated connection may perform any action; check permissions per message.
  • Validate and rate-limit input. Treat incoming frames as untrusted and cap message size and frequency to prevent abuse.

How do you scale WebSocket servers?

Because each connection is stateful and pinned to one server process, scaling differs from stateless HTTP. Two connected users may land on different servers, so a message from one will not reach the other unless the servers share state.

The standard pattern is a shared publish/subscribe backend, commonly Redis, that relays messages between server instances. Each server subscribes to relevant channels and forwards messages to its own connected clients. For connection routing you often need sticky sessions or a load balancer that understands the upgrade, and you should plan for graceful draining during deploys so clients reconnect elsewhere instead of dropping all at once. Capacity planning also matters: each open connection consumes a file descriptor and memory, so a single server has a practical ceiling on concurrent connections that you must load-test rather than guess.

Frequently asked questions

Is a WebSocket the same as HTTP?

No. A WebSocket connection begins as an HTTP request and is then upgraded to the WebSocket protocol, after which it no longer follows the HTTP request-response cycle and stays open for two-way messaging.

What is the difference between ws:// and wss://?

The ws:// scheme is an unencrypted WebSocket connection, while wss:// runs the same protocol over TLS. Always use wss:// in production to protect data in transit.

Do WebSockets work through proxies and firewalls?

Usually, because the handshake looks like HTTP and wss:// on port 443 blends in with normal HTTPS traffic. Some older or strict proxies can still interfere with the connection upgrade.

Are WebSockets better than HTTP polling?

For frequent, low-latency, bidirectional updates they are far more efficient because there is no repeated connection setup or header overhead. For occasional updates, polling or Server-Sent Events may be simpler.

Can WebSockets send binary data?

Yes. A WebSocket message can be a text frame (UTF-8) or a binary frame, so you can send JSON strings, Blobs, ArrayBuffers, or protocol buffers.

How do I detect a dropped WebSocket connection?

Use the close and error events, and implement a heartbeat with ping/pong frames or application-level keepalive messages so you can detect silent failures and reconnect.

Do I need a special server for WebSockets?

You need a server that understands the WebSocket protocol, such as ws or Socket.IO for Node.js, or built-in support in many frameworks. A plain static file host cannot terminate WebSocket connections.

Frequently asked questions

Is a WebSocket the same as HTTP?

No. A WebSocket connection begins as an HTTP request and is then upgraded to the WebSocket protocol, after which it no longer follows the HTTP request-response cycle and stays open for two-way messaging.

What is the difference between ws:// and wss://?

The ws:// scheme is an unencrypted WebSocket connection, while wss:// runs the same protocol over TLS. Always use wss:// in production to protect data in transit.

Do WebSockets work through proxies and firewalls?

Usually, because the handshake looks like HTTP and wss:// on port 443 blends in with normal HTTPS traffic. Some older or strict proxies can still interfere with the connection upgrade.

Are WebSockets better than HTTP polling?

For frequent, low-latency, bidirectional updates they are far more efficient because there is no repeated connection setup or header overhead. For occasional updates, polling or Server-Sent Events may be simpler.

Can WebSockets send binary data?

Yes. A WebSocket message can be a text frame (UTF-8) or a binary frame, so you can send JSON strings, Blobs, ArrayBuffers, or protocol buffers.

How do I detect a dropped WebSocket connection?

Use the close and error events, and implement a heartbeat with ping/pong frames or application-level keepalive messages so you can detect silent failures and reconnect.

Do I need a special server for WebSockets?

You need a server that understands the WebSocket protocol, such as ws or Socket.IO for Node.js, or built-in support in many frameworks. A plain static file host cannot terminate WebSocket connections.

Contact: contact@quikconsolecom.net