
| WebSocket | |
| Industry: | Computer science |
| Connector: | TCP |
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.[1] It is a living standard maintained by the WHATWG and a successor to The WebSocket API from the W3C.[2]
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[3] 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.[4]
Most browsers support the protocol, including Google Chrome, Firefox, Microsoft Edge, Internet Explorer, Safari and Opera.[5]
The WebSocket protocol specification defines ws (WebSocket) and wss (WebSocket Secure) as two new uniform resource identifier (URI) schemes[6] 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.[7]
WebSocket was first referenced as TCPConnection in the HTML5 specification, as a placeholder for a TCP-based socket API.[8] In June 2008, a series of discussions were led by Michael Carter that resulted in the first version of the protocol known as WebSocket.[9] 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,[10] 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.[11] 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.[12]
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.
A web application (e.g. web browser) may use the [[#WebSocket interface|WebSocket]] interface to maintain bidirectional communications with a WebSocket server.[13]
In TypeScript.
// Receive ArrayBuffer instead of Blobws.binaryType = "arraybuffer";
// Set event listeners
ws.onopen = => ;
ws.onmessage = (event: MessageEvent) => ;
ws.onclose = (event: CloseEvent) => ;
ws.onerror = => ;
| Type | Name[14] | Description | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Constructor | ws = new '''WebSocket'''(url [, protocols ]) | Start opening handshake.[15]
Exceptions:
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Method | ws.'''send'''(data) | Send data message.[16]
Return: Exceptions:
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 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ws.'''close'''([ code ] [, reason ]) | Start closing handshake.[17]
Return: Exceptions:
Note:
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Event | ws.'''onopen''' = (event) => {}ws.addEventListener('''"open"''', (event) => {}) | Opening handshake succeeded. event type is Event. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ws.'''onmessage''' = (event) => {}{{nowrap|ws.addEventListener('''"message"''', (event) <nowiki>=></nowiki> {})}}|Data message received. event type is MessageEvent. This event is only fired if ws.readyState is OPEN.[18]
|-|
Note:
|-|
|-| ProtocolSteps:
Opening handshakeThe 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.[33] [34]
Example request: Origin: http://example.comSec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13Example response: The following Python code generates a random print(base64.b64encode(os.urandom(16))) The following Python code calculates KEY: bytes = b"dGhlIHNhbXBsZSBub25jZQ "MAGIC: bytes = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"print(base64.b64encode(hashlib.sha1(KEY + MAGIC).digest))
Though some servers accept a short Frame-based messageAfter the opening handshake, the client and server can, at any time, send data messages (text or binary) and control messages (Close, Ping, Pong) to each other. A message is composed of one frame if unfragmented or at least two frames if fragmented. Fragmentation splits a message into two or more frames. It enables sending messages with initial data available but complete length unknown. Without fragmentation, the whole message must be sent in one frame, so the complete length is needed before the first byte can be sent, which requires a buffer.[50] It was proposed to extend this feature to enable multiplexing several streams simultaneously (e.g. to avoid monopolizing a socket for a single large payload), but the protocol extension was never accepted.[51]
Frame structure
Opcodes
Client-to-server maskingA client must mask all frames sent to the server. A server must not mask any frames sent to the client.[66] Frame masking applies XOR between the payload and the masking key. The following pseudocode describes the algorithm used to both mask and unmask a frame. for i from 0 to payload_length − 1 payload[i] := payload[i] xor masking_key[i mod 4] Status codes
Compression extensionThe Server implementation exampleIn Python. Note: def handle_websocket_connection(ws: Socket) -> None: # Accept connection conn, addr = ws.accept # Receive and parse HTTP request key: Optional[bytes] = None for line in conn.recv(4096).split(b"\r\n"): if line.startswith(b"Sec-WebSocket-Key"): key = line.split[-1] if key is None: raise ValueError("Sec-WebSocket-Key not found") # Send HTTP response sec_accept = base64.b64encode(hashlib.sha1(key + b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest) conn.sendall(b"\r\n".join([b"HTTP/1.1 101 Switching Protocols", b"Connection: Upgrade", b"Upgrade: websocket", b"Sec-WebSocket-Accept: " + sec_accept, b"", b"", ])) # Decode and print frames while True: byte0, byte1 = conn.recv(2) fin: int = byte0 >> 7 opcode: int = byte0 & 0b1111 masked: int = byte1 >> 7 assert masked, "The client must mask all frames" if opcode >= 8: assert fin, "Control frames are unfragmentable" # Payload size payload_size: int = byte1 & 0b111_1111 if payload_size 126: payload_size, = struct.unpack(">H", conn.recv(2)) assert payload_size > 125, "The minimum number of bits must be used" elif payload_size127: payload_size, = struct.unpack(">Q", conn.recv(8)) assert payload_size > 2**16-1, "The minimum number of bits must be used" assert payload_size <= 2**63-1, "The most significant bit must be zero" if opcode >= 8: assert payload_size <= 125, "Control frames must have up to 125 bytes" # Unmask masking_key: bytes = conn.recv(4) payload: bytearray = bytearray(conn.recv(payload_size)) for i in range(payload_size): payload[i] = payload[i] ^ masking_key[i % 4] print("Received frame", FIN, opcode, payload) if __name__ Browser supportA secure version of the WebSocket protocol is implemented in Firefox 6,[70] Safari 6, Google Chrome 14,[71] Opera 12.10 and Internet Explorer 10.[72] A detailed protocol test suite report[73] lists the conformance of those browsers to specific protocol aspects. An older, less secure version of the protocol was implemented in Opera 11 and Safari 5, as well as the mobile version of Safari in iOS 4.2.[74] The BlackBerry Browser in OS7 implements WebSockets.[75] Because of vulnerabilities, it was disabled in Firefox 4 and 5,[76] and Opera 11.[77] Using browser developer tools, developers can inspect the WebSocket handshake as well as the WebSocket frames.[78]
Server implementations
ASP.NET Core have support for WebSockets using the middleware.[93] Security considerationsUnlike regular cross-domain HTTP requests, WebSocket requests are not restricted by the same-origin policy. Therefore, WebSocket servers must validate the "Origin" header against the expected origins during connection establishment, to avoid cross-site WebSocket hijacking attacks (similar to cross-site request forgery), which might be possible when the connection is authenticated with cookies or HTTP authentication. It is better to use tokens or similar protection mechanisms to authenticate the WebSocket connection when sensitive (private) data is being transferred over the WebSocket.[94] A live example of vulnerability was seen in 2020 in the form of Cable Haunt. Proxy traversalWebSocket protocol client implementations try to detect whether the user agent is configured to use a proxy when connecting to destination host and port, and if it is, uses HTTP CONNECT method to set up a persistent tunnel. The WebSocket protocol is unaware of proxy servers and firewalls. Some proxy servers are transparent and work fine with WebSocket; others will prevent WebSocket from working correctly, causing the connection to fail. In some cases, additional proxy-server configuration may be required, and certain proxy servers may need to be upgraded to support WebSocket. If unencrypted WebSocket traffic flows through an explicit or a transparent proxy server without WebSockets support, the connection will likely fail.[95] If an encrypted WebSocket connection is used, then the use of Transport Layer Security (TLS) in the WebSocket Secure connection ensures that an A mid-2010 draft (version hixie-76) broke compatibility with reverse proxies and gateways by including eight bytes of key data after the headers, but not advertising that data in a See also
External links
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||