WebSocket is a computer communications protocol, providing a bidirectional communication channel over a single Transmission Control Protocol (TCP) connection. The protocol was standardized by the IETF as in 2011. The current specification allowing web applications to use this protocol is known as WebSockets. It is a living standard maintained by the WHATWG and a successor to The WebSocket API from the W3C.
WebSocket is distinct from HTTP used to serve most webpages. Although they are different, states that WebSocket "is designed to work over HTTP ports 443 and 80 as well as to support HTTP proxies and intermediaries", making the WebSocket protocol compatible with HTTP. To achieve compatibility, the WebSocket handshake uses the HTTP Upgrade header to change from the HTTP protocol to the WebSocket protocol.
The WebSocket protocol enables full-duplex interaction between a web browser (or other client application) and a web server with lower overhead than half-duplex alternatives such as HTTP polling, facilitating real-time data transfer from and to the server. This is achieved by providing a standardized way for the server to send content to the client without being first requested by the client, and allowing messages to be exchanged while keeping the connection open. In this way, a two-way ongoing conversation can take place between the client and the server. The communications are usually done over TCP port number 443 (or 80 in the case of unsecured connections), which is beneficial for environments that block non-web Internet connections using a firewall. Additionally, WebSocket enables streams of messages on top of TCP. TCP alone deals with streams of bytes with no inherent concept of a message. Similar two-way browser–server communications have been achieved in non-standardized ways using stopgap technologies such as Comet or Adobe Flash Player.
Most browsers support the protocol, including Google Chrome, Firefox, Microsoft Edge, Internet Explorer, Safari and Opera.
The WebSocket protocol specification defines ws (WebSocket) and wss (WebSocket Secure) as two new uniform resource identifier (URI) schemes that are used for unencrypted and encrypted connections respectively. Apart from the scheme name and fragment (i.e. # is not supported), the rest of the URI components are defined to use URI generic syntax.
History WebSocket was first referenced as TCPConnection in the HTML5 specification, as a placeholder for a TCP-based socket API. In June 2008, a series of discussions were led by Michael Carter that resulted in the first version of the protocol known as WebSocket. Before WebSocket, port 80 full-duplex communication was attainable using Comet channels; however, Comet implementation is nontrivial, and due to the TCP handshake and HTTP header overhead, it is inefficient for small messages. The WebSocket protocol aims to solve these problems without compromising the security assumptions of the web. The name "WebSocket" was coined by Ian Hickson and Michael Carter shortly thereafter through collaboration on the #whatwg IRC chat room, and subsequently authored for inclusion in the HTML5 specification by Ian Hickson. In December 2009, Google Chrome 4 was the first browser to ship full support for the standard, with WebSocket enabled by default. Development of the WebSocket protocol was subsequently moved from the W3C and WHATWG group to the IETF in February 2010, and authored for two revisions under Ian Hickson.
After the protocol was shipped and enabled by default in multiple browsers, the was finalized under Ian Fette in December 2011.
introduced compression extension to WebSocket using the DEFLATE algorithm on a per-message basis.
Web API A web application (e.g. web browser) may use the WebSocket interface to maintain bidirectional communications with a WebSocket server.
Client example In TypeScript. // Connect to server const ws = new WebSocket("wss://game.example.com/scoreboard");
// Receive ArrayBuffer instead of Blob ws.binaryType = "arraybuffer";
// Set event listeners
ws.onopen = () => { console.log("Connection opened"); ws.send("Hi server, please send me the score of yesterday's game");
ws.onmessage = (event: MessageEvent) => { console.log("Data received", event.data); ws.close(); // We got the score so we don't need the connection anymore
ws.onclose = (event: CloseEvent) => { console.log("Connection closed", event.code, event.reason, event.wasClean);
ws.onerror = () => { console.log("Connection closed due to error");
WebSocket interface TypeNameDescriptionConstructorws = new WebSocket(url [, protocols ])Start opening handshake.
url: A string containing: Scheme: must be ws, wss, http or https. Host. Optional port: If not specified, 80 is used for ws and http, and 443 for wss and https. Optional path. Optional query. No fragment. Optional protocols: A string or an array of strings used as the value of the Sec-WebSocket-Protocol header in the opening handshake.
Exceptions: SyntaxError: url parsing failed. url has an invalid scheme. url has a fragment. protocols has duplicate strings.Methodws.send(data)Send data message. data: must be string, Blob, ArrayBuffer or ArrayBufferView.
Return: undefined.
Exceptions: InvalidStateError: ws.readyState is CONNECTING.
Note: If the data cannot be sent (e.g. because it would need to be buffered but the buffer is full), the connection is closed and the error event is fired.ws.close([ code ] [, reason ])Start closing handshake.
Optional code: If specified, must be 1000 (Normal closure) or in the range 3000 to 4999 (application-defined). Defaults to 1000. Optional reason: If specified, must be a string whose UTF-8 encoding is up to 123 bytes. Defaults to an empty string.
Return: undefined.
Exceptions: InvalidAccessError: code is not 1000 nor is in the range 3000 to 4999. SyntaxError: UTF-8-encoded reason is longer than 123 bytes.
Note: If ws.readyState is OPEN or CONNECTING, ws.readyState is set to CLOSING and the closing handshake starts. If ws.readyState is CLOSING or CLOSED, nothing happens (because the closing handshake has already started).Eventws.onopen = (event) => {} ws.addEventListener("open", (event) => {})Opening handshake succeeded. event type is Event.ws.onmessage = (event) => {}Data message received. event type is MessageEvent. This event is only fired if ws.readyState is OPEN. event.data is the data received, of type: string for text. Blob or ArrayBuffer for binary (see ws.binaryType). event.origin is ws.url but only with the scheme, host, and port (if any).ws.onclose = (event) => {} ws.addEventListener("close", (event) => {})The underlying TCP connection closed. event type is CloseEvent.
event.code: status code (integer). event.reason: reason for closing (string). event.wasClean: true if the TCP connection was closed after the closing handshake was completed, else false. Note:
If the received Close frame contains a payload, event.code and event.reason get their value from the payload.
If the received Close frame contains no payload, event.code is 1005 (No code received) and event.reason is an empty string.
If no Close frame was received, event.code is 1006 (Connection closed abnormally) and event.reason is an empty string.ws.onerror = (event) => {} ws.addEventListener("error", (event) => {})Connection closed due to error. event type is Event.Attributews.binaryType (string)Type of event.data in ws.onmessage when a binary data message is received. Initially set to "blob" (Blob object). May be changed to "arraybuffer" (ArrayBuffer object).Read-only attributews.url (string)URL given to the WebSocket constructor with the following transformations: If scheme is http or https, change it to ws or wss respectively.ws.bufferedAmount (number)Number of bytes of application data (UTF-8 text and binary data) that have been queued using ws.send() but not yet transmitted to the network. It resets to zero once all queued data has been sent. If the connection closes, this value will only increase, with each call to ws.send(), and never reset to zero.ws.protocol (string)Protocol accepted by the server, or an empty string if protocols was not specified in the WebSocket constructor.ws.extensions (string)Extensions accepted by the server.ws.readyState (number)Connection state. It is one of the constants below. Initially set to CONNECTING.ConstantWebSocket.CONNECTING = 0Opening handshake is currently in progress. The initial state of the connection.WebSocket.OPEN = 1Opening handshake succeeded. The client and server may send messages to each other.WebSocket.CLOSING = 2Closing handshake is currently in progress. Either ws.close() was called or a Close message was received.WebSocket.CLOSED = 3The underlying TCP connection is closed.
Protocol
Steps: Opening handshake: HTTP request and HTTP response. Frame-based message exchange: data, ping and pong messages. Closing handshake: close message (request then echoed in response).
Opening handshake The client sends an HTTP request (method GET, version ≥ 1.1) and the server returns an HTTP response with status code 101 (Switching Protocols) on success. HTTP and WebSocket clients can connect to a server using the same port because the opening handshake uses HTTP. Sending additional HTTP headers (that are not in the table below) is allowed. HTTP headers may be sent in any order. After the Switching Protocols HTTP response, the opening handshake is complete, the HTTP protocol stops being used, and communication switches to a binary frame-based protocol.
+HTTP headers relevant to the opening handshake HeaderValueMandatoryrowspan="4" OriginHostrowspan="6" Sec-WebSocket-Version13Sec-WebSocket-Keybase64-encode(16 random bytes) Sec-WebSocket-Acceptbase64-encode(SHA1(Sec-WebSocket-Key + ))rowspan="4" ConnectionUpgradeUpgradewebsocketSec-WebSocket-ProtocolThe request may contain a comma-separated list of strings (ordered by preference) indicating application-level protocols (built on top of WebSocket data messages) the client wishes to use. If the client sends this header, the server response must be one of the values from the list. rowspan="2" Sec-WebSocket-ExtensionsUsed to negotiate protocol-level extensions. The client may request extensions to the WebSocket protocol by including a comma-separated list of extensions (ordered by preference). Each extension may have a parameter (e.g. foo=4). The server may accept some or all extensions requested by the client. This field may appear multiple times in the request (logically equivalent to a single occurrence containing all values) and must not appear more than once in the response.
Example request:
GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13
Example response:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat
The following Python code generates a random Sec-WebSocket-Key. import base64 import os
print(base64.b64encode(os.urandom(16)))
The following Python code calculates Sec-WebSocket-Accept using Sec-WebSocket-Key from the example request above. import base64 import hashlib
KEY: bytes = b"dGhlIHNhbXBsZSBub25jZQ==" MAGIC: bytes = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" print(base64.b64encode(hashlib.sha1(KEY + MAGIC).digest()))
Sec-WebSocket-Key and Sec-WebSocket-Accept are intended to prevent a caching proxy from re-sending a previous WebSocket conversation, and does not provide any authentication, privacy, or integrity.
Though some servers accept a short Sec-WebSocket-Key, many modern servers will reject the request with error "invalid Sec-WebSocket-Key header".
Frame-based message