What Is a WebSocket? Handshake, Frames, and Full-Duplex Data
Scrapeless Scraping Browser exposes a standard CDP WebSocket endpoint for connecting compatible browser automation frameworks to managed cloud browser sessions.
TL;DR
- WebSocket is full duplex. Client and server can send independently after the handshake.
- The connection starts with HTTP. A successful HTTP/1.1 upgrade returns status 101.
- Messages travel as frames. Text, binary, ping, pong, and close frames have distinct roles.
- wss protects the connection with TLS. Production browser applications should use encrypted WebSocket transport.
- Applications define their own contract. Protocol framing does not create topics, commands, permissions, or replay.
Introduction
A WebSocket is a persistent, full-duplex communication channel that begins with an HTTP-compatible opening handshake and then exchanges WebSocket frames. Either endpoint can send application messages when it has data, without creating a fresh HTTP request for every message.
The protocol supplies framing, control messages, masking rules, close semantics, and origin-related handshake fields. It does not define the application’s message schema, authorization model, event history, or state-recovery strategy. Those remain design work for the service.
The Opening Handshake
The client sends an HTTP request with Upgrade, Connection, Sec-WebSocket-Key, Sec-WebSocket-Version, and often Origin and subprotocol preferences. A server that accepts computes the required Sec-WebSocket-Accept value and returns 101 Switching Protocols.
After that response, ordinary HTTP message semantics no longer frame the data on that connection. RFC 6455 defines the WebSocket protocol, including the handshake fields, registered URI schemes, frame layout, and close codes.
Frames and Messages
Application data is carried in text or binary messages. A message can occupy one frame or be fragmented across several frames. Control frames carry close, ping, and pong signals and have constraints that keep connection management responsive.
Browser clients mask frames they send to servers; servers do not mask frames sent to clients. Masking is not encryption. Use wss so TLS supplies confidentiality, integrity, and server authentication. Message payload validation still belongs to the application.
Full Duplex Changes the API Shape
With request-response HTTP, a client action naturally pairs with a response. WebSocket traffic can arrive in either direction at any time, so the application needs message types, correlation identifiers, ordering rules, error envelopes, and version negotiation.
A command should state whether it expects an acknowledgement, a result, or a stream of updates. Events should include enough identity and version information to apply idempotently. Without an explicit contract, a socket becomes a stream of ambiguous JSON objects that is hard to evolve.
Connection Lifecycle and State Recovery
A WebSocket can close because of application policy, server deployment, idle network state, device sleep, proxy behavior, or path loss. Ping and pong frames can test liveness, but they do not restore missed business events.
Design reconnection separately from state synchronization. After a new connection, the client may send a last-seen event ID, request a snapshot, or resubscribe to topics. The WHATWG WebSockets Standard defines the browser API behavior while leaving application recovery to the service.
Security Boundaries
Validate Origin for browser clients, authenticate the user, authorize every subscription and command, enforce message-size limits, and reject unsupported subprotocols. A connected socket is not permanent authorization; permissions and session expiry can change while it remains open.
Avoid placing durable secrets in URLs because endpoints can appear in logs. Apply rate and concurrency limits per identity, parse payloads defensively, and close connections with controlled codes. TLS protects the transport, while business authorization protects resources.
Scaling and Backpressure
A WebSocket server holds connection state for many clients. Multi-instance deployments need a routing or publish-subscribe layer so an event produced on one node reaches a connection owned by another. Draining connections during deployment also needs an explicit process.
A slow client can accumulate outbound messages faster than the network accepts them. Bound each send queue, coalesce replaceable state updates, and disconnect clients that cannot keep up under a documented policy. MDN’s WebSocket API reference notes that the classic browser interface does not provide built-in backpressure.
| Phase | Wire Behavior | Application Responsibility |
|---|---|---|
| Open | HTTP handshake | Authenticate and choose subprotocol |
| Transfer | Text or binary frames | Define message schema |
| Liveness | Ping and pong control frames | Set idle policy |
| Slow receiver | Frames queue at endpoints | Bound memory and coalesce |
| Reconnect | New connection and handshake | Restore subscriptions and state |
| Close | Close frame and code | Explain policy and release resources |
What Is a WebSocket? Handshake, Frames, and Full-Duplex Data Validation Plan
WebSocket is full duplex. Client and server can send independently after the handshake. Validate that claim across the complete production path. Start with a small representative exchange, record the negotiated behavior at the client and edge, and confirm that the application receives the fields, frames, or events it expects through the same gateway, proxy, certificate termination point, and network policy used by real traffic.
Turn the first design assumption into a failure exercise: Require wss for production endpoints. Then examine resource pressure around the second assumption: Validate browser Origin values. A correct implementation should fail within documented limits, release connection and buffer state, and leave a trace that explains the outcome without exposing credentials or private payloads.
Collaborative editing and Interactive dashboards exercise different parts of the design, so compatibility testing should include both traffic shapes where they are relevant. Add a current browser, a non-browser client, a slower network path, and the oldest supported intermediary. Record version selection, connection lifetime, message or response age, queue depth, and closure reason for the preferred path and its fallback.
Review semantics and transport as separate layers during the test. A successful connection does not prove that the application handled ordering, authorization, cancellation, caching, replay, or state recovery correctly. Likewise, an application error does not prove the negotiated protocol failed. Tag observations with the resource, user scope, logical operation, and connection identifier, then compare what each endpoint believed happened. This separation makes capacity work more useful as well: teams can see whether latency came from connection setup, network delivery, queueing, application processing, serialization, or a slow receiver. Keep private content out of routine telemetry while retaining enough timing and outcome data to reproduce the decision.
Where What Is a WebSocket? Handshake, Frames, and Full-Duplex Data Appears in Practice
Collaborative editing
Peers exchange frequent commands and updates in both directions.
Interactive dashboards
Clients subscribe and can also change filters or issue controls.
Browser automation
CDP clients use a WebSocket endpoint to drive and inspect a remote browser session.
Live market feeds
Servers publish frequent frames while clients adjust subscriptions over the same connection.
What Is a WebSocket? Handshake, Frames, and Full-Duplex Data Production Checklist
- Require wss for production endpoints. Convert this point into a written acceptance test so reviewers can distinguish intended behavior from an accidental implementation detail.
- Validate browser Origin values. Name the component that owns the setting and the person or team that responds when its observed behavior changes.
- Authenticate before accepting privileged subscriptions. Capture the relevant signal in logs or traces, then verify that the signal survives every proxy, gateway, and service boundary in the real path.
- Authorize every message type. Test the decision with a normal case, a slow peer, a closed connection, an oversized input, and a version or capability mismatch.
- Set maximum frame and message sizes. Document the safe default and the exact condition that permits an exception; hidden exceptions become interoperability problems during later changes.
- Define ping, idle, and close policies. Check this behavior from a representative browser or client instead of relying only on a local unit test or a server-side configuration screen.
- Bound outbound queues per connection. Set a finite resource limit and make the resulting rejection visible to both operators and the calling application.
- Version the application message contract. Preserve enough identifiers to correlate one logical exchange across the client, edge, application, and any asynchronous worker.
- Provide snapshot or cursor-based state recovery. Review the choice after a traffic-shape change because connection count, payload size, and message frequency can alter the correct design.
- Drain and observe connections during deployments. Keep the fallback path observable and tested so compatibility does not depend on an old path that silently stopped working.
Conclusion
WebSocket is full duplex. Client and server can send independently after the handshake. Applications define their own contract. Protocol framing does not create topics, commands, permissions, or replay. Apply those two facts with explicit limits, observable state, and a fallback that is tested by representative clients rather than assumed from configuration.
Ready to Build a Reliable Web Data Workflow?
Turn protocol decisions into observable browser and API workflows with Scrapeless.
Sign up today and get $5 in free credit — no credit card required.
Claim Your $5 Credit →FAQ
Is WebSocket an HTTP protocol?
WebSocket uses an HTTP-compatible opening handshake, then switches to its own framing protocol on the established connection.
What is the difference between ws and wss?
ws is an unencrypted WebSocket URI scheme, while wss protects the connection with TLS and is the normal production choice.
Can WebSocket send binary data?
Yes. WebSocket defines separate text and binary data frame types, and the application decides how to interpret binary payloads.
Does WebSocket reconnect automatically?
The browser WebSocket API does not provide automatic reconnection or state recovery; the application must define those behaviors.
Does a WebSocket guarantee message delivery?
A live connection uses reliable transport, but application delivery across disconnects requires acknowledgements, persistence, deduplication, and resynchronization as needed.