The WebSocket API is a browser programming interface through which code uses a WebSocket object to create and manage a two-way, message-based connection to a WebSocket-capable server. The interface exposes properties, methods and events to application code; the WebSocket protocol defines the opening handshake and framing rules that package messages for transmission. The API is widely available in modern browsers, although support for individual features can vary.
How the Connection Works
In the RFC 6455 model, WebSocket carries traffic in both directions over one TCP connection. Persistent means that this connection remains in use across messages until it closes or fails. Full-duplex means that, after successful opening and before an endpoint sends Close, either side can send independently without waiting for a corresponding application request or response. The server therefore both handles the opening request and participates in ongoing messaging.
Ordinary HTTP uses request–response exchanges; polling repeatedly requests updates. The WebSocket API can avoid polling and per-message HTTP request headers, potentially reducing overhead and update latency for suitable traffic. The distinction is not connection reuse: HTTP/1.1 also supports multiple exchanges over a persistent connection.
Consider a mobile app that requests the latest entries in a feed. The response body might contain a JSON list of entries. Another response might carry the bytes of a thumbnail. HTTP/1.1 can carry either kind of content over a connection the client reuses. A WebSocket becomes useful when the app needs to receive later updates as they happen, even between requests.
Chat, stock-ticker updates and interactive games fit this model because messages may be frequent or unsolicited. For example, in a hypothetical chat application, the browser sends a user's message and receives new messages from the server over the same connection, without repeatedly asking whether anything has arrived. “Real-time” here does not promise instantaneous delivery or a fixed deadline.
Opening the Connection
Creating a WebSocket object initiates a connection attempt, not an immediately usable channel. In the RFC 6455 TCP-based opening model, the browser sends an HTTP Upgrade request. The server parses it and either rejects it with an HTTP error or returns a 101 Switching Protocols response with the required acceptance information. Only after the browser validates that response does the connection become open.
A client can use Sec-WebSocket-Protocol to offer subprotocols that define how the application interprets messages. Under RFC 6455, the server can select one of those values or select none. The browser API adds a stricter rule. If browser code supplies a nonempty list, the server must confirm one of the offered values. If it confirms none, the browser fails the opening handshake. Code that offers no subprotocol can open a connection without one. Selecting a subprotocol does not grant access.
Advertisement — FinchTrade.
FinchTrade services
Get startedBrowser Interface and Message Types
The WebSocket API exposes the connection's current state through readyState. An open event signals successful opening; while open, send() queues outgoing data, and message events deliver incoming messages to application code, including through an onmessage handler. These are interface operations, distinct from the protocol's framing and transmission work.
Messages can contain text or binary data. Binary payloads could carry image or file contents, but the application must define their interpretation and any transfer workflow. The binaryType property controls how received binary data is represented in the browser, not its file format or meaning.
Security and Access
A ws:// connection is unencrypted; wss:// uses TLS to protect connection confidentiality and integrity. TLS must succeed before the protected WebSocket opening can proceed, and transport protection does not replace application access controls.
The browser supplies Sec-WebSocket-Key, a nonce used for handshake validation—not a password or encryption key. Its Origin header identifies the initiating script's origin, allowing servers to restrict unwanted browser cross-origin use. Origin is not authentication because non-browser clients can forge it. Neither successful upgrade nor subprotocol selection proves identity or permission: restricted applications still need authentication and authorization, using appropriate mechanisms such as cookies, HTTP authentication or TLS authentication.
Closure and Delivery Limits
In the WebSocket API, close() requests closure, while the close event reports that the connection has closed; error events report failures. Either endpoint can start orderly closure by sending a Close control frame and must then stop sending application data. The peer responds with Close unless it has already sent one, including when both initiate simultaneously. Completion of the exchange leads to transport shutdown, but errors or connection loss can terminate communication without completing it.
Neither send(), an open state nor completed closure confirms that every message reached or was processed by the other application. Applications needing such confirmation must define acknowledgements above the basic WebSocket exchange.