WebSocket

Uses your system voice; voice and rate in settings.

Snapshot

≈ 8 min read

Names in other languages

No names in other languages are held for this entry yet.

Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.

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.…

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. // 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"); }; 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". An unfragmented message consists of one frame with FIN = 1 and opcode ≠ 0 . A fragmented message consists of one frame with FIN = 0 and opcode ≠ 0 , followed by zero or more frames with FIN = 0 and opcode = 0 , and terminated by one frame with FIN = 1 and opcode = 0 . payload[i] := payload[i] xor masking_key[i mod 4] Sec-WebSocket-Extensions: permessage-deflate import base64 import hashlib import struct from typing import Optional from socket import socket as Socket 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_size == 127: 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 = 8: assert payload_size

Text derived from https://en.wikipedia.org/w/index.php?oldid=1376734210 under CC BY-SA 4.0; modifications have been made.