Qortora · Search · Indexed page

websockets.spec.whatwg.orgFetched 2026-08-14T19:29:28Z

WebSockets Standard

WebSockets Standard WebSockets Living Standard — Last Updated 15 March 2026 Participate: GitHub whatwg/websockets (new issue, open issues) Chat on Matrix Commits: GitHub whatwg/websockets/commits Snapshot as of this commit @whatsockets Tests: web-platform-tests websockets/ (ong…

Open original source · Full cached text

WebSockets Standard WebSockets Living Standard — Last Updated 15 March 2026 Participate: GitHub whatwg/websockets (new issue, open issues) Chat on Matrix Commits: GitHub whatwg/websockets/commits Snapshot as of this commit @whatsockets Tests: web-platform-tests websockets/ (ongoing work) Translations (non-normative): 日本語 简体中文 한국어 Abstract This specification provides APIs to enable web applications to maintain bidirectional communications with server-side processes. 1. Introduction This section is non-normative. To enable web applications to maintain bidirectional communications with server-side processes, this specification introduces the WebSocket interface. This interface does not allow for raw access to the underlying network. For example, this interface could not be used to implement an IRC client without proxying messages through a custom server. 2. WebSocket protocol alterations This section replaces part of the WebSocket protocol opening handshake client requirement to integrate it with algorithms defined in Fetch. This way CSP, cookies, HSTS, and other Fetch-related protocols are handled in a single location. Ideally the RFC would be updated with this language, but it is never that easy. The WebSocket API, defined below, uses this language. [WSP] [FETCH] The way this works is by replacing The WebSocket Protocol’s "establish a WebSocket connection" algorithm with a new one that integrates with Fetch. "Establish a WebSocket connection" consists of three algorithms: setting up a connection, creating and transmiting a handshake request, and validating the handshake response. That layering is different from Fetch, which first creates a handshake, then sets up a connection and transmits the handshake, and finally validates the response. Keep that in mind while reading these alterations. 2.1. Connections To obtain a WebSocket connection, given a url, run these steps: Let host be url’s host. Let port be url’s port. Let resource name be U+002F (/), followed by the strings in url’s path (including empty strings), if any, separated from each other by U+002F (/). If url’s query is non-empty, append U+003F (?), followed by url’s query, to resource name. Let secure be false, if url’s scheme is "http"; otherwise true. Follow the requirements stated in step 2 to 5, inclusive, of the first set of steps in section 4.1 of The WebSocket Protocol to establish a WebSocket connection, passing host, port, resource name and secure. [WSP] If that established a connection, return it, and return failure otherwise. Although structured a little differently, carrying different properties, and therefore not shareable, a WebSocket connection is very close to identical to an "ordinary" connection. 2.2. Opening handshake To establish a WebSocket connection, given a url, protocols, and client, run these steps: Let requestURL be a copy of url, with its scheme set to "http", if url’s scheme is "ws"; otherwise to "https". This change of scheme is essential to integrate well with fetching. E.g., HSTS would not work without it. There is no real reason for WebSocket to have distinct schemes, it’s a legacy artefact. [HSTS] Let request be a new request, whose URL is requestURL, client is client, service-workers mode is "none", referrer is "no-referrer", mode is "websocket", credentials mode is "include", cache mode is "no-store" , and redirect mode is "error". Append (`Upgrade`, `websocket`) to request’s header list. Append (`Connection`, `Upgrade`) to request’s header list. Let keyValue be a nonce consisting of a randomly selected 16-byte value that has been forgiving-base64-encoded and isomorphic encoded. If the randomly selected value was the byte sequence 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f 0x10, keyValue would be forgiving-base64-encoded to "AQIDBAUGBwgJCgsMDQ4PEC==" and isomorphic encoded to `AQIDBAUGBwgJCgsMDQ4PEC==`. Append (`Sec-WebSocket-Key`, keyValue) to request’s header list. Append (`Sec-WebSocket-Version`, `13`) to request’s header list. For each protocol in protocols, combine (`Sec-WebSocket-Protocol`, protocol) in request’s header list. Let permessageDeflate be a user-agent defined "permessage-deflate" extension header value. [WSP] `permessage-deflate; client_max_window_bits` Append (`Sec-WebSocket-Extensions`, permessageDeflate) to request’s header list. Fetch request with useParallelQueue set to true, and processResponse given response being these steps: If response is a network error or its status is not 101, fail the WebSocket connection. If protocols is not the empty list and extracting header list values given `Sec-WebSocket-Protocol` and response’s header list results in null, failure, or the empty byte sequence, then fail the WebSocket connection. This is different from the check on this header defined by The WebSocket Protocol. That only covers a subprotocol not requested by the client. This covers a subprotocol requested by the client, but not acknowledged by the server. Follow the requirements stated step 2 to step 6, inclusive, of the last set of steps in section 4.1 of The WebSocket Protocol to validate response. This either results in fail the WebSocket connection or the WebSocket connection is established. Fail the WebSocket connection and the WebSocket connection is established are defined by The WebSocket Protocol. [WSP] The reason redirects are not followed and this handshake is generally restricted is because it could introduce serious security problems in a web browser context. For example, consider a host with a WebSocket server at one path and an open HTTP redirector at another. Suddenly, any script that can be given a particular WebSocket URL can be tricked into communicating to (and potentially sharing secrets with) any host on the internet, even if the script checks that the URL has the right hostname. 3. The WebSocket interface 3.1. Interface definition The Web IDL definition for the WebSocket class is given as follows: enum BinaryType { "blob", "arraybuffer" }; [Exposed=(Window,Worker)] interface WebSocket : EventTarget { constructor(USVString url, optional (DOMString or sequence<DOMString>) protocols = []); readonly attribute USVString url; // ready state const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSING = 2; const unsigned short CLOSED = 3; readonly attribute unsigned short readyState; readonly attribute unsigned long long bufferedAmount; // networking attribute EventHandler onopen; attribute EventHandler onerror; attribute EventHandler onclose; readonly attribute DOMString extensions; readonly attribute DOMString protocol; undefined close(optional [Clamp] unsigned short code, optional USVString reason); // messaging attribute EventHandler onmessage; attribute BinaryType binaryType; undefined send((BufferSource or Blob or USVString) data); }; Each WebSocket object has an associated url, which is a URL record. Each WebSocket object has an associated binary type, which is a BinaryType. Initially it must be "blob". Each WebSocket object has an associated ready state, which is a number representing the state of the connection. Initially it must be CONNECTING (0). It can have the following values: CONNECTING (numeric value 0) The connection has not yet been established. OPEN (numeric value 1) The WebSocket connection is established and communication is possible. CLOSING (numeric value 2) The connection is going through the closing handshake, or the close() method has been invoked. CLOSED (numeric value 3) The connection has been closed or could not be opened. socket = new WebSocket(url [, protocols ]) Creates a new WebSocket object, immediately establishing the associated WebSocket connection. url is a string giving the URL over which the connection is established. Only "ws", "wss", "http", and "https" schemes are allowed; others will cause a "SyntaxError" DOMException. URLs with fragments will always cause such an exception. protocols is either a string or an array of strings. If it is a string, it is equivalent to an array consisting of just that string; if it is omitted, it is equivalent to the empty array. Each string in the array is a subprotocol name. The connection will only be established if the server reports that it has selected one of these subprotocols. The subprotocol names have to match the requirements for elements that comprise the value of `Sec-WebSocket-Protocol` fields as defined by The WebSocket protocol. [WSP] socket.send(data) Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. socket.close([ code ] [, reason ]) Closes the WebSocket connection, optionally using code as the WebSocket connection close code and reason as the WebSocket connection close reason. socket.url Returns the URL that was used to establish the WebSocket connection. socket.readyState Returns the state of the WebSocket connection. It can have the values described above. socket.bufferedAmount Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network. If the WebSocket connection is closed, this attribute’s value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.) socket.extensions Returns the extensions selected by the server, if any. socket.protocol Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor’s second argument to perform subprotocol negotiation. socket.binaryType Returns a string that indicates how binary data from socket is exposed to scripts: "blob" Binary data is returned in Blob form. "arraybuffer" Binary data is returned in ArrayBuffer form. The default is "blob". socket.binaryType = value Changes how binary data is returned. The new WebSocket(url, protocols) constructor steps are: Let baseURL be this’s relevant settings object’s API base URL. Let urlRecord be the result of applying the URL parser to url with baseURL. If urlRecord is failure, then throw a "SyntaxError" DOMException. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. If urlRecord’s fragment is non-null, then throw a "SyntaxError" DOMException. If protocols is a string, set protocols to a sequence consisting of just that string. If any of the values in protocols occur more than once or otherwise fail to match the requirements for elements that comprise the value of `Sec-WebSocket-Protocol` fields as defined by The WebSocket protocol, then throw a "SyntaxError" DOMException. [WSP] Set this’s url to urlRecord. Let client be this’s relevant settings object. Run this step in parallel: Establish a WebSocket connection given urlRecord, protocols, and client. [FETCH] If the establish a WebSocket connection algorithm fails, it triggers the fail the WebSocket connection algorithm, which then invokes the close the WebSocket connection algorithm, which then establishes that the WebSocket connection is closed, which fires the close event as described below. The url getter steps are to return this’s url, serialized. The readyState getter steps are to return this’s ready state. The extensions attribute must initially return the empty string. After the WebSocket connection is established, its value might change, as defined below. The protocol attribute must initially return the empty string. After the WebSocket connection is established, its value might change, as defined below. The close(code, reason) method steps are: If code is present, but is neither an integer equal to 1000 nor an integer in the range 3000 to 4999, inclusive, throw an "InvalidAccessError" DOMException.…