WebSocket

WebSocket

WebSocket

Computer network protocol


WebSocket is a computer communications protocol, providing simultaneous two-way communication channels over a single Transmission Control Protocol (TCP) connection. The WebSocket protocol was standardized by the IETF as RFC 6455 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]

Quick Facts International standard, Developed by ...

WebSocket is distinct from HTTP used to serve most webpages. Although they are different, RFC 6455 states that WebSocket "is designed to work over HTTP ports 443 and 80 as well as to support HTTP proxies and intermediaries", thus making it 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 made possible 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 passed back and forth 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]

History

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 RFC 6455 was finalized under Ian Fette in December 2011.

RFC 7692 introduced compression extension to WebSocket using the DEFLATE algorithm on a per-message basis.

Client example

<!DOCTYPE doc>
<script>
// Connect to server
ws = new WebSocket("ws://localhost/scoreboard") // Current computer
// ws = new WebSocket("wss://game.example.com/scoreboard") // Computer somewhere

ws.onopen = () => {
    console.log("Connection opened")
    ws.send("Hi server, please send me the score for yesterday's game")
}

ws.onmessage = (event) => {
    console.log("Data received", event.data)
    ws.close() // We got the score so we don't need the connection anymore
}

ws.onclose = (event) => {
    console.log("Connection closed", event.code, event.reason, event.wasClean)
}

ws.onerror = () => {
    console.log("Connection closed due to error")
}
</script>

Server example

from socket import socket
from base64 import b64encode
from hashlib import sha1

MAGIC = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

# Create socket and listen at port 80
ws = socket()
ws.bind(("", 80))
ws.listen()
conn, addr = ws.accept()

# Parse request
for line in conn.recv(4096).split(b"\r\n"):
    if line.startswith(b"Sec-WebSocket-Key"):
        nonce = line.split(b":")[1].strip()

# Format response
response = f"""\
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: {b64encode(sha1(nonce + MAGIC).digest()).decode()}

"""

conn.send(response.replace("\n", "\r\n").encode())

while True: # decode messages from the client
    header = conn.recv(2)
    FIN = bool(header[0] & 0x80) # bit 0
    assert FIN == 1, "We only support unfragmented messages"
    opcode = header[0] & 0xf # bits 4-7
    assert opcode == 1 or opcode == 2, "We only support data messages"
    masked = bool(header[1] & 0x80) # bit 8
    assert masked, "The client must mask all frames"
    payload_size = header[1] & 0x7f # bits 9-15
    assert payload_size <= 125, "We only support small messages"
    masking_key = conn.recv(4)
    payload = bytearray(conn.recv(payload_size))
    for i in range(payload_size):
        payload[i] = payload[i] ^ masking_key[i % 4]
    print(payload)

Web API

A web application (e.g. web browser) may use the WebSocket interface to connect to a WebSocket server.

More information Type, Name ...

Protocol

Steps:

  1. Opening handshake (HTTP request + HTTP response) to establish a connection.
  2. Data messages to transfer application data.
  3. Closing handshake (two Close frames) to close the connection.

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. This means a WebSocket server can use the same port as HTTP (80) and HTTPS (443) because the handshake is compatible with HTTP.[27]

More information Side, Header ...

Example request:[37]

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

Example response:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

In HTTP each line ends in \r\n and the last line is empty.

# Calculate Sec-WebSocket-Accept using Sec-WebSocket-Key
from base64 import b64encode
from hashlib import sha1
from os import urandom
# key = b64encode(urandom(16)) # Client should do this
key = b"x3JJHMbDL1EzLkh9GBhXDw==" # Value in example request above
magic = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" # Protocol constant
print(b64encode(sha1(key + magic).digest()))
# Output: HSmrc0sMlYUkAGmm5OPpG2HaGWk=

Once the connection is established, communication switches to a binary frame-based protocol which does not conform to the HTTP protocol.

Sec-WebSocket-Key and Sec-WebSocket-Accept are intended to prevent a caching proxy from re-sending a previous WebSocket conversation,[38] 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

After the opening handshake, the client and server can, at any time, send messages to each other, such as data messages (text or binary) and control messages (close, ping, pong). A message is composed of one or more frames.

Fragmentation allows a message to be split 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.[39] It also enables multiplexing several streams simultaneously (e.g. to avoid monopolizing a socket for a single large payload).[40]

  • An unfragmented message consists of a single frame with FIN = 1 and opcode ≠ 0.
  • A fragmented message consists of a single frame with FIN = 0 and opcode ≠ 0, followed by zero or more frames with FIN = 0 and opcode = 0, and terminated by a single frame with FIN = 1 and opcode = 0.

Frame structure

More information Index (in bits), Field ...

Opcodes

More information ...

Status codes

More information Range, Allowed in Close frame ...

Browser support

A secure version of the WebSocket protocol is implemented in Firefox 6,[52] Safari 6, Google Chrome 14,[53] Opera 12.10 and Internet Explorer 10.[54] A detailed protocol test suite report[55] 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.[56] The BlackBerry Browser in OS7 implements WebSockets.[57] Because of vulnerabilities, it was disabled in Firefox 4 and 5,[58] and Opera 11.[59] Using browser developer tools, developers can inspect the WebSocket handshake as well as the WebSocket frames.[60]

More information ProtocolVersion, Draft date ...

Server implementations

  • Apache HTTP Server has supported WebSockets since July, 2013, implemented in version 2.4.5[71][72]
  • Internet Information Services added support for WebSockets in version 8 which was released with Windows Server 2012.[73]
  • lighttpd has supported WebSockets since 2017, implemented in version 1.4.46.[74] lighttpd mod_proxy can act as a reverse proxy and load balancer of WebSocket applications. lighttpd mod_wstunnel can construct WebSocket tunnels to transmit arbitrary data, including in JSON format, to a backend application.

Security considerations

Unlike 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.[75] A live example of vulnerability was seen in 2020 in the form of Cable Haunt.

Proxy traversal

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

While the WebSocket protocol itself is unaware of proxy servers and firewalls, it features an HTTP-compatible handshake, thus allowing HTTP servers to share their default HTTP and HTTPS ports (80 and 443 respectively) with a WebSocket gateway or server. The WebSocket protocol defines a ws:// and wss:// prefix to indicate a WebSocket and a WebSocket Secure connection respectively. Both schemes use an HTTP upgrade mechanism to upgrade to the WebSocket protocol. 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.[76]

If an encrypted WebSocket connection is used, then the use of Transport Layer Security (TLS) in the WebSocket Secure connection ensures that an HTTP CONNECT command is issued when the browser is configured to use an explicit proxy server. This sets up a tunnel, which provides low-level end-to-end TCP communication through the HTTP proxy, between the WebSocket Secure client and the WebSocket server. In the case of transparent proxy servers, the browser is unaware of the proxy server, so no HTTP CONNECT is sent. However, since the wire traffic is encrypted, intermediate transparent proxy servers may simply allow the encrypted traffic through, so there is a much better chance that the WebSocket connection will succeed if WebSocket Secure is used. Using encryption is not free of resource cost, but often provides the highest success rate, since it would be travelling through a secure tunnel.

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 Content-Length: 8 header.[77] This data was not forwarded by all intermediates, which could lead to protocol failure. More recent drafts (e.g., hybi-09[78]) put the key data in a Sec-WebSocket-Key header, solving this problem.

See also

Notes

  1. Gecko-based browsers versions 6–10 implement the WebSocket object as "MozWebSocket",[63] requiring extra code to integrate with existing WebSocket-enabled code.

References

  1. "WebSockets Standard". websockets.spec.whatwg.org. Retrieved 2022-05-16.
  2. "The WebSocket API". www.w3.org. Retrieved 2022-05-16.
  3. Ian Fette; Alexey Melnikov (December 2011). "Relationship to TCP and HTTP". RFC 6455 The WebSocket Protocol. IETF. sec. 1.7. doi:10.17487/RFC6455. RFC 6455.
  4. "Adobe Flash Platform – Sockets". help.adobe.com. Retrieved 2021-07-28. TCP connections require a "client" and a "server". Flash Player can create client sockets.
  5. "The WebSocket API (WebSockets)". MDN Web Docs. Mozilla Developer Network. 2023-04-06. Archived from the original on 2021-07-28. Retrieved 2021-07-26.
  6. Ian Fette; Alexey Melnikov (December 2011). "WebSocket URIs". RFC 6455 The WebSocket Protocol. IETF. sec. 3. doi:10.17487/RFC6455. RFC 6455.
  7. "HTML 5". www.w3.org. Retrieved 2016-04-17.
  8. "IRC logs: freenode / #whatwg / 20080618". krijnhoetmer.nl. Retrieved 2016-04-18.
  9. "Web Sockets Now Available In Google Chrome". Chromium Blog. Retrieved 2016-04-17.
  10. <[email protected]>, Ian Hickson (6 May 2010). "The WebSocket protocol". Ietf Datatracker. Retrieved 2016-04-17.
  11. "OPEN". WHATWG.
  12. "CLOSING". WHATWG.
  13. "CLOSED". WHATWG.
  14. "Main Goal of WebSocket protocol". IETF. Retrieved 25 July 2015. The computation [...] is meant to prevent a caching intermediary from providing a WS-client with a cached WS-server reply without actual interaction with the WS-server.
  15. John A. Tamplin; Takeshi Yoshino (2013). A Multiplexing Extension for WebSockets. IETF. I-D draft-ietf-hybi-websocket-multiplexing.
  16. Dirkjan Ochtman (May 27, 2011). "WebSocket enabled in Firefox 6". Mozilla.org. Archived from the original on 2012-05-26. Retrieved 2011-06-30.
  17. "Chromium Web Platform Status". Retrieved 2011-08-03.
  18. "WebSockets (Windows)". Microsoft. 2012-09-28. Retrieved 2012-11-07.
  19. "WebSockets Protocol Test Report". Tavendo.de. 2011-10-27. Archived from the original on 2016-09-22. Retrieved 2011-12-10.
  20. Katie Marsal (November 23, 2010). "Apple adds accelerometer, WebSockets support to Safari in iOS 4.2". AppleInsider.com. Retrieved 2011-05-09.
  21. "Web Sockets API". BlackBerry. Archived from the original on June 10, 2011. Retrieved 8 July 2011.
  22. Chris Heilmann (December 8, 2010). "WebSocket disabled in Firefox 4". Hacks.Mozilla.org. Retrieved 2011-05-09.
  23. Aleksander Aas (December 10, 2010). "Regarding WebSocket". My Opera Blog. Archived from the original on 2010-12-15. Retrieved 2011-05-09.
  24. Wang, Vanessa; Salim, Frank; Moskovits, Peter (February 2013). "APPENDIX A: WebSocket Frame Inspection with Google Chrome Developer Tools". The Definitive Guide to HTML5 WebSocket. Apress. ISBN 978-1-4302-4740-1. Archived from the original on 31 December 2015. Retrieved 7 April 2013.
  25. "WebSockets (support in Firefox)". developer.mozilla.org. Mozilla Foundation. 2011-09-30. Archived from the original on 2012-05-26. Retrieved 2011-12-10.
  26. "Bug 640003 - WebSockets - upgrade to ietf-06". Mozilla Foundation. 2011-03-08. Retrieved 2011-12-10.
  27. "WebSockets - MDN". developer.mozilla.org. Mozilla Foundation. 2011-09-30. Archived from the original on 2012-05-26. Retrieved 2011-12-10.
  28. "Chromium bug 64470". code.google.com. 2010-11-25. Retrieved 2011-12-10.
  29. "WebSockets in Windows Consumer Preview". IE Engineering Team. Microsoft. 2012-03-19. Retrieved 2012-07-23.
  30. "A hot Opera 12.50 summer-time snapshot". Opera Developer News. 2012-08-03. Archived from the original on 2012-08-05. Retrieved 2012-08-03.
  31. "Welcome to nginx!". nginx.org. Archived from the original on 17 July 2012. Retrieved 3 February 2022.
  32. "IIS 8.0 WebSocket Protocol Support". Microsoft Docs. 28 November 2012. Retrieved 2020-02-18.
  33. Christian Schneider (August 31, 2013). "Cross-Site WebSocket Hijacking (CSWSH)". Web Application Security Blog.
  34. Peter Lubbers (March 16, 2010). "How HTML5 Web Sockets Interact With Proxy Servers". Infoq.com. C4Media Inc. Retrieved 2011-12-10.
  35. Willy Tarreau (2010-07-06). "WebSocket -76 is incompatible with HTTP reverse proxies". ietf.org (email). Internet Engineering Task Force. Retrieved 2011-12-10.
  36. Ian Fette (June 13, 2011). "Sec-WebSocket-Key". The WebSocket protocol, draft hybi-09. sec. 11.4. Retrieved June 15, 2011.

Share this article:

This article uses material from the Wikipedia article WebSocket, and is written by contributors. Text is available under a CC BY-SA 4.0 International License; additional terms may apply. Images, videos and audio are available under their respective licenses.