WebSocket#Opening handshake
{{short description|Computer network protocol}}
{{Infobox protocol
| name = WebSocket
| image = WebSocket colored logo.svg
| caption = The WebSocket logo
| standard = {{IETF RFC|6455}}
| developer = IETF
| introdate =
| industry = Computer science
| connector = TCP
| hardware =
| range =
| newer =
}}
WebSocket is a computer communications protocol, providing a simultaneous two-way communication channel over a single Transmission Control Protocol (TCP) connection. The WebSocket protocol was standardized by the IETF as {{IETF RFC|6455}} in 2011. The current specification allowing web applications to use this protocol is known as WebSockets.{{Cite web |title=WebSockets Standard |url=https://websockets.spec.whatwg.org/ |access-date=2022-05-16 |website=websockets.spec.whatwg.org |archive-date=2023-03-12 |archive-url=https://web.archive.org/web/20230312232711/https://websockets.spec.whatwg.org/ |url-status=live }} It is a living standard maintained by the WHATWG and a successor to The WebSocket API from the W3C.{{Cite web |title=The WebSocket API |url=https://www.w3.org/TR/2021/NOTE-websockets-20210128/Overview.html |access-date=2022-05-16 |website=www.w3.org |language=en |archive-date=2022-06-08 |archive-url=https://web.archive.org/web/20220608221509/https://www.w3.org/TR/2021/NOTE-websockets-20210128/Overview.html |url-status=live }}
WebSocket is distinct from HTTP used to serve most webpages. Although they are different, {{IETF 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{{Cite IETF |title=RFC 6455 The WebSocket Protocol |publisher = IETF |section=1.7 |sectionname=Relationship to TCP and HTTP |rfc=6455 |date=December 2011|author1=Ian Fette |author2=Alexey Melnikov}} 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.{{Cite web |title=Adobe Flash Platform – Sockets |url=https://help.adobe.com/en_US/as3/dev/WSb2ba3b1aad8a27b0-181c51321220efd9d1c-8000.html |access-date=2021-07-28 |website=help.adobe.com |quote=TCP connections require a "client" and a "server". Flash Player can create client sockets. |archive-date=2021-04-18 |archive-url=https://web.archive.org/web/20210418211002/https://help.adobe.com/en_US/as3/dev/WSb2ba3b1aad8a27b0-181c51321220efd9d1c-8000.html |url-status=live }}
Most browsers support the protocol, including Google Chrome, Firefox, Microsoft Edge, Internet Explorer, Safari and Opera.{{Cite web |date=2023-04-06 |title=The WebSocket API (WebSockets) |url=https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API |url-status=live |archive-url=https://web.archive.org/web/20210728161324/https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API |archive-date=2021-07-28 |access-date=2021-07-26 |website=MDN Web Docs |publisher=Mozilla Developer Network |language=en-US}}
The WebSocket protocol specification defines ws
(WebSocket) and wss
(WebSocket Secure) as two new uniform resource identifier (URI) schemes{{cite web |url=https://www.iana.org/assignments/uri-schemes.html |title=IANA Uniform Resource Identifier (URI) Schemes |publisher=Internet Assigned Numbers Authority |date=2011-11-14 |access-date=2011-12-10 |editor=Graham Klyne |archive-date=2013-04-25 |archive-url=https://web.archive.org/web/20130425164755/http://www.iana.org/assignments/uri-schemes.html |url-status=live }} 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.{{Cite IETF |title=RFC 6455 The WebSocket Protocol |publisher=IETF |section=3 |sectionname=WebSocket URIs |rfc=6455 |date=December 2011 |author1=Ian Fette |author2=Alexey Melnikov}}
History
WebSocket was first referenced as TCPConnection in the HTML5 specification, as a placeholder for a TCP-based socket API.{{Cite web|url=https://www.w3.org/TR/2008/WD-html5-20080610/comms.html#tcp-connections|title=HTML 5|website=www.w3.org|access-date=2016-04-17|archive-date=2016-09-16|archive-url=https://web.archive.org/web/20160916071246/http://www.w3.org/TR/2008/WD-html5-20080610/comms.html#tcp-connections|url-status=live}} In June 2008, a series of discussions were led by Michael Carter that resulted in the first version of the protocol known as WebSocket.{{Cite web|url=https://lists.w3.org/Archives/Public/public-whatwg-archive/2008Jun/0165.html|title=[whatwg] TCPConnection feedback from Michael Carter on 2008-06-18 (whatwg.org from June 2008)|website=lists.w3.org|access-date=2016-04-17|archive-date=2016-04-27|archive-url=https://web.archive.org/web/20160427004936/https://lists.w3.org/Archives/Public/public-whatwg-archive/2008Jun/0165.html|url-status=live}}
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,{{Cite web|url=http://krijnhoetmer.nl/irc-logs/whatwg/20080618#l-1145|title=IRC logs: freenode / #whatwg / 20080618|website=krijnhoetmer.nl|access-date=2016-04-18|archive-date=2016-08-21|archive-url=https://web.archive.org/web/20160821040755/http://krijnhoetmer.nl/irc-logs/whatwg/20080618#l-1145|url-status=live}} 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.{{Cite web|url=https://blog.chromium.org/2009/12/web-sockets-now-available-in-google.html|title=Web Sockets Now Available In Google Chrome|website=Chromium Blog|language=en-US|access-date=2016-04-17|archive-date=2021-12-09|archive-url=https://web.archive.org/web/20211209195505/https://blog.chromium.org/2009/12/web-sockets-now-available-in-google.html|url-status=live}} 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.{{Cite journal|url=https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75|title=The WebSocket protocol|last=
After the protocol was shipped and enabled by default in multiple browsers, the {{IETF RFC|6455}} was finalized under Ian Fette in December 2011.
{{IETF RFC|7692}} introduced compression extension to WebSocket using the DEFLATE algorithm on a per-message basis.
Examples
= Client example =
// Connect to server
ws = new WebSocket("ws://127.0.0.1/scoreboard") // Local server
// ws = new WebSocket("wss://game.example.com/scoreboard") // Remote server
ws.onopen = () => {
console.log("Connection opened")
ws.send("Hi server, please send me the score of 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")
}
= Server example =
In Python.
from socket import socket
from base64 import b64encode
from hashlib import sha1
import struct
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"):
Sec_WebSocket_Key = line.split(b":")[1].strip()
- Format response
response = f"""\
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: {b64encode(sha1(Sec_WebSocket_Key + 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]
conn.send(struct.pack("BB", 0x80 | opcode, payload_size) + payload) # echo message
print("Received", "text" if opcode == 1 else "binary", "message", payload)
Web API
A web application (e.g. web browser) may use the WebSocket
interface to maintain bidirectional communications with a WebSocket server.{{Cite web|title=Introduction|url=https://websockets.spec.whatwg.org/#network-intro|website=WHATWG}}
class="wikitable"
|+WebSocket interface specification{{Cite web |title=Interface definition |url=https://websockets.spec.whatwg.org/#interface-definition |website=WHATWG |access-date=2024-04-10 |archive-date=2023-03-12 |archive-url=https://web.archive.org/web/20230312232711/https://websockets.spec.whatwg.org/#interface-definition |url-status=live }} !Type !Name !Description |
Constructor
|
|
rowspan="2" |Method
| |Send data.{{Cite web |title=send(data) |url=https://websockets.spec.whatwg.org/#dom-websocket-send |website=WHATWG}} |
ws.close([ code ] [, reason ])
|
rowspan="4" |Event
|
|Opening handshake succeeded. |
ws.onmessage = (event) => {}
|Data received.{{Cite web|title=When a WebSocket message has been received|url=https://websockets.spec.whatwg.org/#:~:text=When%20a%20WebSocket%20message%20has%20been%20received|website=WHATWG}}
|
ws.onclose = (event) => {}
|The underlying TCP connection closed.
Note:
|
ws.onerror = (event) => {}
|Connection closed due to error. |
Attribute
| |A string indicating the type of |
rowspan="5" |Read-only attribute
| |The URL given to the
|
ws.bufferedAmount
|The number of bytes of application data (UTF-8 text and binary data) that have been queued using |
ws.protocol
|The protocol accepted by the server, or an empty string if the client did not specify |
ws.extensions
|The extensions accepted by the server. |
ws.readyState
|The connection state. It is one of the constants below. Initially set to |
rowspan="4" |Constant
| |Waiting opening handshake.{{Cite web |title=CONNECTING |url=https://websockets.spec.whatwg.org/#ref-for-dom-websocket-connecting%E2%91%A0 |website=WHATWG |access-date=2024-04-13 |archive-date=2023-03-12 |archive-url=https://web.archive.org/web/20230312232711/https://websockets.spec.whatwg.org/#ref-for-dom-websocket-connecting%E2%91%A0 |url-status=live }}{{Cite IETF|rfc=6455|title=Client Requirements|section=4.1|page=14}} |
WebSocket.OPEN = 1
|Opening handshake succeeded. The client and server may message each other.{{Cite web |title=OPEN |url=https://websockets.spec.whatwg.org/#dom-websocket-open |website=WHATWG |access-date=2024-04-10 |archive-date=2023-03-12 |archive-url=https://web.archive.org/web/20230312232711/https://websockets.spec.whatwg.org/#dom-websocket-open |url-status=live }}{{Cite IETF|rfc=6455|title=_The WebSocket Connection is Established_|page=20}} |
WebSocket.CLOSING = 2
|Waiting closing handshake. Either |
WebSocket.CLOSED = 3
|The underlying TCP connection is closed.{{Cite web|title=CLOSED|url=https://websockets.spec.whatwg.org/#dom-websocket-closed|website=WHATWG|access-date=2024-04-10|archive-date=2023-03-12|archive-url=https://web.archive.org/web/20230312232711/https://websockets.spec.whatwg.org/#dom-websocket-closed|url-status=live}} |
Protocol
File: Websocket connection.png
Steps:
- Opening handshake: HTTP request + HTTP response.
- Exchange frame-based messages: application data, ping and pong messages.
- Closing handshake: request + response Close frames.
= 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 handshake is compatible with HTTP. Sending additional HTTP headers (that are not in the table below) is allowed. HTTP headers may be sent in any order.{{Cite IETF|title=Opening Handshake|rfc=6455|section=1.3}}{{Cite IETF|title=Protocol Overview|section=1.2|rfc=6455}}
class="wikitable" style="text-align:center"
|+HTTP headers relevant to the opening handshake ! {{verth|Side}} !Header !Value !Mandatory |
rowspan="4" {{verth|Request|va=middle}}
|Origin{{Cite IETF|rfc=6455|page=18|title=Client requirement 8..}} |{{Varies}} |{{yes|Yes (for browser clients)}} |
Host{{Cite IETF|rfc=6455|page=17|title=Client requirement 4..}}
|{{Varies}} |rowspan="6" {{Yes}} |
Sec-WebSocket-Version{{Cite IETF|rfc=6455|title=Client requirement 9..|page=18}}
|13 |
Sec-WebSocket-Key{{Cite IETF|rfc=6455|page=18|title=Client requirement 7..}} |
{{verth|Response}}
|Sec-WebSocket-Accept{{Cite IETF|rfc=6455|title=Server step 5.4..|page=24}} |base64-encode(sha1(Sec-WebSocket-Key + {{nowrap|"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"}})) |
rowspan="4" {{verth|Both|va=middle}}
|Connection{{Cite IETF|rfc=6455|title=Client requirement 6..|page=18}}{{Cite IETF|rfc=6455|title=Server step 5.3.|page=24}} |Upgrade |
Upgrade{{Cite IETF|rfc=6455|title=Client requirement 5..|page=17}}{{Cite IETF|rfc=6455|title=Server step 5.2.|page=24}}
|websocket |
Sec-WebSocket-Protocol{{Cite IETF|rfc=6455|title=Client requirement 10..|page=18}}
|The 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" {{no}} |
Sec-WebSocket-Extensions{{Cite IETF|rfc=6455|title=Client requirement 11..|page=19}}{{Cite IETF|rfc=6455|title=Sec-WebSocket-Extensions|section=11.3.2}}{{Cite IETF|rfc=6455|title=Extensions|section=9}}{{Cite IETF|rfc=6455|title=Negotiating Extensions|section=9.1}}
|Used 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 calculates Sec-WebSocket-Accept
using Sec-WebSocket-Key
from the example above.
import base64, hashlib
Sec_WebSocket_Key = b"dGhlIHNhbXBsZSBub25jZQ=="
MAGIC = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
- Sec-WebSocket-Accept
print(base64.b64encode(hashlib.sha1(Sec_WebSocket_Key + MAGIC).digest()))
Sec-WebSocket-Key
and Sec-WebSocket-Accept
are intended to prevent a caching proxy from re-sending a previous WebSocket conversation,{{cite web |title=Main Goal of WebSocket protocol |url=https://trac.tools.ietf.org/wg/hybi/trac/wiki/FAQ |access-date=25 July 2015 |publisher=IETF |quote=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. |archive-date=22 April 2016 |archive-url=https://web.archive.org/web/20160422042232/https://trac.tools.ietf.org/wg/hybi/trac/wiki/FAQ |url-status=live }} 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".
After the Switching Protocols HTTP response, the HTTP protocol stops being used, and communication switches to a binary frame-based protocol explained below.
= Frame-based message =
After 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 not fragmented 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. It also enables multiplexing several streams simultaneously (e.g. to avoid monopolizing a socket for a single large payload).{{Cite IETF|section=5.4|rfc=6455|title=Fragmentation}}{{cite IETF|draft=draft-ietf-hybi-websocket-multiplexing|title=A Multiplexing Extension for WebSockets|author1=John A. Tamplin|author2=Takeshi Yoshino|publisher=IETF|year=2013}}
- An unfragmented message consists of one frame with
FIN = 1
andopcode ≠ 0
. - A fragmented message consists of one frame with
FIN = 0
andopcode ≠ 0
, followed by zero or more frames withFIN = 0
andopcode = 0
, and terminated by one frame withFIN = 1
andopcode = 0
.
= Frame structure =
class="wikitable"
!Index ! colspan="2" |Field !Size !Description |
0
| colspan="2" |FIN{{Cite IETF|rfc=6455|title=FIN|page=28}} |1 |{{ulist|1=1 = final frame of a message. |2=0 = message is fragmented and this is not the final frame.}} |
1
| colspan="2" |RSV1 |1 |rowspan="3"|Must be 0 unless defined by an extension. If a non-zero value is received and none of the negotiated extensions defines the meaning of such a non-zero value, the connection must be closed. {{Cite IETF|rfc=6455|title=RSV1, RSV2, RSV3|page=28}} |
2
| colspan="2" |RSV2 |1 |
3
| colspan="2" |RSV3 |1 |
4
| colspan="2" |Opcode |4 |See opcodes below. |
8
| colspan="2" |Masked{{Cite IETF|rfc=6455|title=Mask|page=29}} |1 |{{ulist|1=1 = frame is masked (i.e. masking key is present and the payload has been XORed with masking key). |2=0 = frame is not masked (i.e. masking key is not present).}} See client-to-server masking below. |
9
| colspan="2" |Payload length{{Cite IETF|rfc=6455|title=Payload length|page=29}} |7, 7+16 or 7+64 |Length of the payload (extension data + application data) in bytes. {{ulist|1=0–125 = This is the payload length. |2=126 = The following 16 bits are the payload length. |3=127 = The following 64 bits (MSB must be 0) are the payload length.}} Endianness is big-endian. Signedness is unsigned. The minimum number of bits must be used to encode the length. |
rowspan="3" {{varies}}
| colspan="2" |Masking key |0 or 32 |{{anchor|Client-to-server masking}}{{nowrap|A client must mask all frames sent to the server.}} A server must not mask any frames sent to the client.{{Cite IETF|title=Overview|section=5.1|rfc=6455}} Frame masking applies XOR between the masking key (a four-byte random nonce) and the payload. The following pseudocode describes the algorithm used to both mask and unmask a frame:{{Cite IETF|title=Client-to-Server Masking|section=5.3|rfc=6455}} for i = 0 to payload_length - 1 payload[i] = payload[i] xor masking_key[i modulo 4] |
rowspan="2"|Payload
|Extension data |rowspan="2"|Payload length (in bytes) |Must be empty unless defined by an extension. |
Application data
|{{Depends}} on the opcode |
= Opcodes =
class="wikitable"
! colspan="2" |Frame type !Opcode !Related !Description !Purpose !{{vertical header|Fragmentable}} !Max. payload length |
colspan="2" align="center" |Continuation
|0 | |Non-first frame of a fragmented message. |Fragmentation | |rowspan="4"|{{tmath|2^{63}-1}} bytes |
rowspan="2" |Data frame
|Text |1 | rowspan="2" | |UTF-8-encoded application text. |rowspan="2"|Application data |rowspan="3" {{Yes}} |
Binary
|2 |Application binary data. |
colspan="2" |
|3–7 | |{{n/a|Reserved for further non-control frames yet to be defined}} | |
rowspan="4" |Control frame{{Cite IETF|title=Control Frames|section=5.5|rfc=6455}}
|Close |8 | |{{anchor|Closing handshake}}A Close frame is sent to start the closing handshake which may prevent data loss by complementing the TCP closing handshake.{{Cite IETF|title=Closing Handshake|section=1.4|rfc=6455}} No frame can be sent after a Close frame. If a Close frame is received and no prior Close frame was sent, a response Close frame with the same payload must be sent. The payload is optional, but if present, it must start with a two-byte big-endian unsigned integer status code, optionally followed by a UTF-8-encoded reason message not longer than 123 bytes.{{Cite IETF|title=Close|section=5.5.1|rfc=6455}} |rowspan="4"|Protocol state |rowspan="4" {{No}} |rowspan="4"|125 bytes |
Ping
|9 | |rowspan="2"|{{nowrap|May be used for latency measurement}}, keepalive and heartbeat. Both sides can initiate a ping (with any payload). Whoever receives it must, as soon as is practical, send back a pong with the same payload. A pong should be ignored if no prior ping was sent.{{Cite IETF|title=Ping|section=5.5.2|rfc=6455}}{{Cite IETF|title=Pong|section=5.5.3|rfc=6455}}{{cite web|title=Ping and Pong frames|website=WHATWG|url=https://websockets.spec.whatwg.org/#ping-and-pong-frames}} |
Pong
|10 | |
|11–15
| |{{n/a|Reserved for further control frames yet to be defined}} |
= Status codes =
class="wikitable"
!Range{{Cite IETF|section=7.4.2|rfc=6455|title=Reserved Status Code Ranges}} !Allowed in Close frame !Code {{Cite IETF|section=7.4.1|rfc=6455|title=Defined Status Codes}} !Description |
0–999
|{{No}} | |{{n/a|Unused}} |
rowspan="13" |1000–2999 (Protocol)
| rowspan="4" {{Yes}} |1000 |Normal closure. |
1001
|Going away (e.g. browser tab closed; server going down). |
1002
|Protocol error. |
1003
|Unsupported data (e.g. endpoint only understands text but received binary). |
rowspan="3" {{No}}
|1004 |{{n/a|Reserved for future usage}} |
1005
|No code received. |
1006
|Connection closed abnormally (i.e. closing handshake did not occur). |
rowspan="5" {{Yes}}
|1007 |Invalid payload data (e.g. non UTF-8 data in a text message). |
1008
|Policy violated. |
1009
|Message too big. |
1010
|Unsupported extension. The client should write the extensions it expected the server to support in the payload. |
1011
|Internal server error. |
{{No}}
|1015 |TLS handshake failure. |
3000–3999
| rowspan="2" {{Yes}} | |Reserved for libraries, frameworks and applications. Registered directly with IANA. |
4000–4999
| |Private use. |
Browser support
A secure version of the WebSocket protocol is implemented in Firefox 6,{{cite web | url=https://developer.mozilla.org/en/WebSockets | title=WebSocket enabled in Firefox 6 | author=Dirkjan Ochtman | date=May 27, 2011 | work=Mozilla.org | access-date=2011-06-30 | archive-date=2012-05-26 | archive-url=https://web.archive.org/web/20120526230019/https://developer.mozilla.org/en/WebSockets | url-status=dead }} Safari 6, Google Chrome 14,{{cite web | url=https://www.chromium.org/developers/web-platform-status | title=Chromium Web Platform Status | access-date=2011-08-03 | archive-date=2017-03-04 | archive-url=https://web.archive.org/web/20170304203008/http://www.chromium.org/developers/web-platform-status | url-status=live }} Opera 12.10 and Internet Explorer 10.{{cite web |url=https://msdn.microsoft.com/en-us/library/ie/hh673567(v=vs.85).aspx |title=WebSockets (Windows) |publisher=Microsoft |date=2012-09-28 |access-date=2012-11-07 |archive-date=2015-03-25 |archive-url=https://web.archive.org/web/20150325091443/https://msdn.microsoft.com/en-us/library/ie/hh673567(v=vs.85).aspx |url-status=live }} A detailed protocol test suite report{{cite web |url=http://autobahn.ws/testsuite/reports/clients/index.html |title=WebSockets Protocol Test Report |publisher=Tavendo.de |date=2011-10-27 |access-date=2011-12-10 |archive-date=2016-09-22 |archive-url=https://web.archive.org/web/20160922040928/http://autobahn.ws/testsuite/reports/clients/index.html |url-status=dead }} 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.{{cite web | url=https://www.appleinsider.com/articles/10/11/23/apple_adds_accelerometer_websockets_support_to_safari_in_ios_4_2.html | title=Apple adds accelerometer, WebSockets support to Safari in iOS 4.2 | author=Katie Marsal | date=November 23, 2010 | work=AppleInsider.com | access-date=2011-05-09 | archive-date=2011-03-01 | archive-url=https://web.archive.org/web/20110301114256/http://www.appleinsider.com/articles/10/11/23/apple_adds_accelerometer_websockets_support_to_safari_in_ios_4_2.html | url-status=live }} The BlackBerry Browser in OS7 implements WebSockets.{{cite web|title=Web Sockets API |url=http://docs.blackberry.com/en/developers/deliverables/29271/Web_Sockets_support_1582781_11.jsp |publisher=BlackBerry |access-date=8 July 2011 |url-status=dead |archive-url=https://web.archive.org/web/20110610191150/http://docs.blackberry.com/en/developers/deliverables/29271/Web_Sockets_support_1582781_11.jsp |archive-date=June 10, 2011 }} Because of vulnerabilities, it was disabled in Firefox 4 and 5,{{cite web | url=https://hacks.mozilla.org/2010/12/websockets-disabled-in-firefox-4/ | title=WebSocket disabled in Firefox 4 | author=Chris Heilmann | date=December 8, 2010 | work=Hacks.Mozilla.org | access-date=2011-05-09 | archive-date=2017-03-06 | archive-url=https://web.archive.org/web/20170306114251/https://hacks.mozilla.org/2010/12/websockets-disabled-in-firefox-4/ | url-status=live }} and Opera 11.{{cite web | url=http://my.opera.com/chooseopera/blog/2010/12/10/regarding-websocket | title=Regarding WebSocket | author=Aleksander Aas | date=December 10, 2010 | work=My Opera Blog | access-date=2011-05-09 |archive-url=https://web.archive.org/web/20101215010748/http://my.opera.com/chooseopera/blog/2010/12/10/regarding-websocket|archive-date=2010-12-15}}
Using browser developer tools, developers can inspect the WebSocket handshake as well as the WebSocket frames.{{cite book |last1=Wang |first1=Vanessa |last2=Salim |first2=Frank |last3=Moskovits |first3=Peter |title=The Definitive Guide to HTML5 WebSocket |chapter-url=http://my.safaribooksonline.com/book/-/9781430247401/appendix-a-inspecting-websocket-traffic/sec1_xhtml |access-date=7 April 2013 |date=February 2013 |publisher=Apress |isbn=978-1-4302-4740-1 |chapter=APPENDIX A: WebSocket Frame Inspection with Google Chrome Developer Tools |archive-date=31 December 2015 |archive-url=https://web.archive.org/web/20151231184436/http://my.safaribooksonline.com/book/-/9781430247401/appendix-a-inspecting-websocket-traffic/sec1_xhtml |url-status=dead }}
class="wikitable" style="text-align:right"
! {{diagonal split header|2=Protocol|1=Version}} ! Draft date ! Internet Explorer ! Firefox ! Chrome ! Safari ! Opera ! Android Browser |
[https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 hixie-75]
| February 4, 2010 | | | | 4 | 5.0.0 | | |
---|
[https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 hixie-76] [https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00 hybi-00] | May 6, 2010 | | 4.0 | | 6 | 5.0.1 | 11.00 | |
[https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07 hybi-07], v7
| April 22, 2011 | | 6{{cite web |url=https://bugzilla.mozilla.org/show_bug.cgi?id=640003 |title=Bug 640003 - WebSockets - upgrade to ietf-06 |publisher=Mozilla Foundation |date=2011-03-08 |access-date=2011-12-10 |archive-date=2021-04-01 |archive-url=https://web.archive.org/web/20210401044535/https://bugzilla.mozilla.org/show_bug.cgi?id=640003 |url-status=live }}{{Efn|name="mozwebsocket"|Gecko-based browsers versions 6–10 implement the WebSocket object as "MozWebSocket",{{cite web |url=https://developer.mozilla.org/en/WebSockets |title=WebSockets - MDN |website=developer.mozilla.org |publisher=Mozilla Foundation |date=2011-09-30 |access-date=2011-12-10 |archive-date=2012-05-26 |archive-url=https://web.archive.org/web/20120526230019/https://developer.mozilla.org/en/WebSockets |url-status=dead }} requiring extra code to integrate with existing WebSocket-enabled code.}} | | | | | |
[https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10 hybi-10], v8
| July 11, 2011 | | 7 | | | |
{{IETF RFC|6455}}, v13
| December, 2011 | 11 | 11 | 6 | 4.4 |
Server implementations
- Nginx has supported WebSockets since 2013, implemented in version 1.3.13{{cite web |url=http://nginx.org/en/CHANGES |title=Welcome to nginx! |website=nginx.org |access-date=3 February 2022 |archive-url=https://archive.today/20120717014311/http://nginx.org/en/CHANGES |archive-date=17 July 2012 |url-status=dead}} including acting as a reverse proxy and load balancer of WebSocket applications.{{Cite web|url=https://www.nginx.com/blog/websocket-nginx/|title=Using NGINX as a WebSocket Proxy|date=May 17, 2014|website=NGINX|access-date=November 3, 2019|archive-date=October 6, 2019|archive-url=https://web.archive.org/web/20191006062348/https://www.nginx.com/blog/websocket-nginx/|url-status=live}}
- Apache HTTP Server has supported WebSockets since July, 2013, implemented in version 2.4.5{{Cite web|url=http://httpd.apache.org/docs/trunk/new_features_2_4.html|title=Overview of new features in Apache HTTP Server 2.4|website=Apache|access-date=2021-01-26|archive-date=2020-11-11|archive-url=https://web.archive.org/web/20201111201741/http://httpd.apache.org/docs/trunk/new_features_2_4.html|url-status=live}}{{Cite web|url=https://www.apachelounge.com/Changelog-2.4.html|title=Changelog Apache 2.4|website=Apache Lounge|access-date=2021-01-26|archive-date=2021-01-22|archive-url=https://web.archive.org/web/20210122162741/https://www.apachelounge.com/Changelog-2.4.html|url-status=live}}
- Internet Information Services added support for WebSockets in version 8 which was released with Windows Server 2012.{{cite web | url=https://docs.microsoft.com/en-us/iis/get-started/whats-new-in-iis-8/iis-80-websocket-protocol-support | title=IIS 8.0 WebSocket Protocol Support | date=28 November 2012 | work=Microsoft Docs | access-date=2020-02-18 | archive-date=2020-02-18 | archive-url=https://web.archive.org/web/20200218153735/https://docs.microsoft.com/en-us/iis/get-started/whats-new-in-iis-8/iis-80-websocket-protocol-support | url-status=live }}
- lighttpd has supported WebSockets since 2017, implemented in lighttpd 1.4.46.{{cite web | url=https://redmine.lighttpd.net/projects/lighttpd/wiki/Release-1_4_46 | title=Release-1 4 46 - Lighttpd - lighty labs | access-date=2020-12-29 | archive-date=2021-01-16 | archive-url=https://web.archive.org/web/20210116155634/https://redmine.lighttpd.net/projects/lighttpd/wiki/Release-1_4_46 | url-status=live }} lighttpd mod_proxy can act as a reverse proxy and load balancer of WebSocket applications. lighttpd mod_wstunnel can act as a WebSocket endpoint to transmit arbitrary data, including in JSON format, to a backend application. lighttpd supports WebSockets over HTTP/2 since 2022, implemented in lighttpd 1.4.65.{{cite web | url=https://redmine.lighttpd.net/projects/lighttpd/wiki/Release-1_4_65 | title=Release-1 4 65 - Lighttpd - lighty labs | access-date=2024-05-03 | archive-date=2024-05-03 | archive-url=https://web.archive.org/web/20240503061036/https://redmine.lighttpd.net/projects/lighttpd/wiki/Release-1_4_65 | url-status=live }}
ASP.NET Core have support for WebSockets using the {{Code|app.UseWebSockets();}} middleware.{{cite web |title=WebSockets support in ASP.NET Core |url=https://learn.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-9.0 |website=learn.microsoft.com |access-date=2 May 2025 |language=en-us}}
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.{{cite web |url=https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html#main |title=Cross-Site WebSocket Hijacking (CSWSH) |author=Christian Schneider |work=Web Application Security Blog |date=August 31, 2013 |access-date=December 30, 2015 |archive-date=December 31, 2016 |archive-url=https://web.archive.org/web/20161231061757/http://www.christian-schneider.net/CrossSiteWebSocketHijacking.html#main |url-status=live }} 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.{{cite web |url=http://www.infoq.com/articles/Web-Sockets-Proxy-Servers |title=How HTML5 Web Sockets Interact With Proxy Servers |website=Infoq.com |date=March 16, 2010 |publisher=C4Media Inc. |author=Peter Lubbers |access-date=2011-12-10 |archive-date=2016-05-08 |archive-url=https://web.archive.org/web/20160508202722/http://www.infoq.com/articles/Web-Sockets-Proxy-Servers |url-status=live }}
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.{{cite web |url=https://www.ietf.org/mail-archive/web/hybi/current/msg02149.html |title=WebSocket -76 is incompatible with HTTP reverse proxies |website=ietf.org |publisher=Internet Engineering Task Force |date=2010-07-06 |access-date=2011-12-10 |author=Willy Tarreau |type=email |archive-date=2016-09-17 |archive-url=https://web.archive.org/web/20160917063052/http://www.ietf.org/mail-archive/web/hybi/current/msg02149.html |url-status=live }} This data was not forwarded by all intermediates, which could lead to protocol failure. More recent drafts (e.g., hybi-09{{cite IETF |url=https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-09#section-11.4 |title=The WebSocket protocol, draft hybi-09 |sectionname=Sec-WebSocket-Key |section=11.4 |date=June 13, 2011 |access-date=June 15, 2011 |author=Ian Fette }} {{Webarchive|url=https://web.archive.org/web/20160201000218/http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-09#section-11.4 |date=February 1, 2016 }}) put the key data in a Sec-WebSocket-Key
header, solving this problem.
See also
{{Div col|colwidth=22em}}
- BOSH
- Comparison of WebSocket implementations
- Network socket
- Push technology
- Server-sent events
- XMLHttpRequest
- HTTP/2
- Internet protocol suite
- WebRTC
{{div col end}}
Notes
{{Notelist}}
References
{{Reflist}}
External links
- [https://datatracker.ietf.org/wg/hybi/charter/ IETF Hypertext-Bidirectional (HyBi) working group]
- {{IETF RFC|6455}} The WebSocket protocol – Proposed Standard published by the IETF HyBi Working Group
- [https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol The WebSocket protocol] – Internet-Draft published by the IETF HyBi Working Group
- [https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 The WebSocket protocol] – Original protocol proposal by Ian Hickson
- [https://dev.w3.org/html5/websockets/ The WebSocket API] {{Webarchive|url=https://web.archive.org/web/20150607035919/http://dev.w3.org/html5/websockets/ |date=2015-06-07 }} – W3C Working Draft specification of the API
- [http://www.w3.org/TR/websockets/ The WebSocket API] – W3C Candidate Recommendation specification of the API
- [https://www.websocket.org/ WebSocket.org] {{Webarchive|url=https://web.archive.org/web/20180916101105/http://websocket.org/ |date=2018-09-16 }} WebSocket demos, loopback tests, general information and community
{{Web browsers|fsp}}
{{Web interfaces}}