# WebSocket

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/WebSocket
> Markdown URL: https://mediated.wiki/source/WebSocket.md
> Source: https://en.wikipedia.org/wiki/WebSocket
> Source revision: 1344988474
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

{{short description|Computer network protocol}}
{{Infobox protocol
| name        = WebSocket
| image       = WebSocket colored logo.svg
| caption     = The WebSocket logo
| standard    = {{ubl|{{IETF RFC|6455}}|[https://websockets.spec.whatwg.org WebSockets]}}
| developer   = {{ubl|[IETF](/source/IETF)|[WHATWG](/source/WHATWG)}}
| introdate = {{Start date|2011|12}}
| industry    = [Computer science](/source/Computer_science)
| connector   = [TCP](/source/Transmission_Control_Protocol)
| website =
}}

'''WebSocket''' is a computer [communications protocol](/source/communications_protocol), providing a [bidirectional](/source/full-duplex) communication channel over a single [Transmission Control Protocol](/source/Transmission_Control_Protocol) (TCP) connection. The protocol was standardized by the [IETF](/source/Internet_Engineering_Task_Force) as {{IETF RFC|6455}} in 2011. The current specification allowing web applications to use this protocol is known as ''WebSockets''.<ref>{{Cite web |title=WebSockets Standard |url=https://websockets.spec.whatwg.org/ |access-date=2022-05-16 |website=WHATWG WebSockets|archive-date=2023-03-12 |archive-url=https://web.archive.org/web/20230312232711/https://websockets.spec.whatwg.org/ |url-status=live }}</ref> It is a living standard maintained by the [WHATWG](/source/Web_Hypertext_Application_Technology_Working_Group) and a successor to ''The WebSocket API'' from the [W3C](/source/World_Wide_Web_Consortium).<ref>{{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 }}</ref>

WebSocket is distinct from [HTTP](/source/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", making the WebSocket protocol compatible with HTTP. To achieve compatibility, the WebSocket [handshake](/source/Handshake_(computing)) uses the [HTTP Upgrade header](/source/HTTP%2F1.1_Upgrade_header)<ref>{{Cite IETF |title=RFC 6455 The WebSocket Protocol |publisher = [IETF](/source/Internet_Engineering_Task_Force) |section=1.7 |sectionname=Relationship to TCP and HTTP |rfc=6455 |date=December 2011|author1=Ian Fette |author2=Alexey Melnikov}}</ref> to change from the HTTP protocol to the WebSocket protocol.

The WebSocket protocol enables [full-duplex](/source/Duplex_(telecommunications)) interaction between a [web browser](/source/web_browser) (or other [client](/source/Client_(computing)) application) and a [web server](/source/web_server) with lower overhead than half-duplex alternatives such as HTTP [polling](/source/Polling_(computer_science)), 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](/source/Port_(computer_networking)) number 443 (or 80 in the case of unsecured connections), which is beneficial for environments that block non-web Internet connections using a [firewall](/source/Firewall_(computing)). 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](/source/Comet_(programming)) or [Adobe Flash Player](/source/Adobe_Flash_Player).<ref>{{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 }}</ref>

Most browsers support the protocol, including [Google Chrome](/source/Google_Chrome), [Firefox](/source/Firefox), [Microsoft Edge](/source/Microsoft_Edge), [Internet Explorer](/source/Internet_Explorer), [Safari](/source/Safari_(web_browser)) and [Opera](/source/Opera_web_browser).<ref>{{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}}</ref>

The WebSocket protocol specification defines <code>ws</code> (WebSocket) and <code>wss</code> (WebSocket Secure) as two new [uniform resource identifier](/source/uniform_resource_identifier) (URI) schemes<ref>{{cite web |url=https://www.iana.org/assignments/uri-schemes.html |title=IANA Uniform Resource Identifier (URI) Schemes |publisher=[Internet Assigned Numbers Authority](/source/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 }}</ref> that are used for unencrypted and encrypted connections respectively. Apart from the scheme name and [fragment](/source/Fragment_identifier) (i.e. <code>#</code> is not supported), the rest of the URI components are defined to use [URI generic syntax](/source/Path_segment).<ref>{{Cite IETF |title=RFC 6455 The WebSocket Protocol |publisher=[IETF](/source/Internet_Engineering_Task_Force) |section=3 |sectionname=WebSocket URIs |rfc=6455 |date=December 2011 |author1=Ian Fette |author2=Alexey Melnikov}}</ref>

==History==
WebSocket was first referenced as TCPConnection in the [HTML5](/source/HTML5) specification, as a placeholder for a TCP-based socket API.<ref>{{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}}</ref> In June 2008, a series of discussions were led by [Michael Carter](/source/Michael_Carter_(entrepreneur)) that resulted in the first version of the protocol known as WebSocket.<ref>{{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}}</ref>
Before WebSocket, port 80 full-duplex communication was attainable using [Comet](/source/Comet_(programming)) 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](/source/Ian_Hickson) and Michael Carter shortly thereafter through collaboration on the #whatwg IRC chat room,<ref>{{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}}</ref> 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.<ref>{{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}}</ref> Development of the WebSocket protocol was subsequently moved from the W3C and [WHATWG](/source/WHATWG) group to the IETF in February 2010, and authored for two revisions under Ian Hickson.<ref>{{Cite journal|url=https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75|title=The WebSocket protocol|last=<ian@hixie.ch>|first=Ian Hickson|newspaper=Ietf Datatracker|date=6 May 2010|access-date=2016-04-17|archive-date=2017-03-17|archive-url=https://web.archive.org/web/20170317201023/https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75|url-status=live}}</ref>

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](/source/DEFLATE) algorithm on a per-message basis.

== Web API ==
A web application (e.g. web browser) may use the <code>WebSocket</code> interface to maintain bidirectional communications with a WebSocket server.<ref>{{Cite web|title=Introduction|url=https://websockets.spec.whatwg.org/#network-intro|website=WHATWG WebSockets|at=sec. 1.}}</ref>

=== Client example ===
In [TypeScript](/source/TypeScript).
<syntaxhighlight lang="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");
};
</syntaxhighlight>

=== WebSocket interface ===
{| class="wikitable"
!Type
!Name<ref>{{Cite web |title=Interface definition |url=https://websockets.spec.whatwg.org/#interface-definition |website=WHATWG WebSockets|at=sec. 3.1.|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 }}</ref>
!Description
|-
|[Constructor](/source/Constructor_(object-oriented_programming))
|<code>ws = new '''WebSocket'''(url [, protocols ])</code>
|'''Start opening handshake'''.<ref>{{Cite web |title=new WebSocket(url, protocols) |url=https://websockets.spec.whatwg.org/#dom-websocket-websocket |website=WHATWG WebSockets|at=sec. 3.1.|access-date=2024-04-30 |archive-date=2023-03-12 |archive-url=https://web.archive.org/web/20230312232711/https://websockets.spec.whatwg.org/#dom-websocket-websocket |url-status=live }}</ref>

* <code>'''[url](/source/url)'''</code>: A string containing:
** '''[Scheme](/source/URL)''': must be <code>ws</code>, <code>wss</code>, <code>http</code> or <code>https</code>.
** '''[Host](/source/URL)'''.
** Optional [port](/source/URL): If not specified, 80 is used for <code>ws</code> and <code>http</code>, and 443 for <code>wss</code> and <code>https</code>.
** Optional [path](/source/URL).
** Optional [query](/source/URL).
** '''No''' [fragment](/source/URL).
* Optional <code>protocols</code>: A string or an array of strings used as the value of the <code>Sec-WebSocket-Protocol</code> header in the opening handshake.

Exceptions:
* <code>SyntaxError</code>:
**<code>url</code> parsing{{efn|The '''URL parsing algorithm''' is described at https://url.spec.whatwg.org/#concept-basic-url-parser}} failed.
**<code>url</code> has an invalid scheme.
**<code>url</code> has a fragment.
**<code>protocols</code> has duplicate strings.
|-
| rowspan="2" |[Method](/source/Method_(computer_programming))
|<code>ws.'''send'''(data)</code>
|'''Send data message'''.<ref>{{Cite web |title=send(data) |url=https://websockets.spec.whatwg.org/#dom-websocket-send |website=WHATWG WebSockets |at=sec. 3.1.}}</ref>
* <code>data</code>: must be <code>string</code>, <code>Blob</code>, <code>ArrayBuffer</code> or <code>ArrayBufferView</code>.

Return: <code>undefined</code>.

Exceptions:
* <code>InvalidStateError</code>: <code>ws.readyState</code> is <code>CONNECTING</code>.

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 <code>error</code> event is fired.
|-
|<code>ws.'''close'''([ code ] [, reason ])</code>
|'''Start''' '''closing handshake'''.<ref>{{Cite web |title=close(code, reason) |url=https://websockets.spec.whatwg.org/#dom-websocket-close |website=WHATWG WebSockets|at=sec. 3.1.|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-close |url-status=live }}</ref>

* Optional <code>code</code>: If specified, must be 1000 (''Normal closure'') or in the range 3000 to 4999 (application-defined). Defaults to 1000.
* Optional <code>reason</code>: If specified, must be a string whose [UTF-8](/source/UTF-8) encoding is up to 123 bytes. Defaults to an empty string.

Return: <code>undefined</code>.

Exceptions:
* <code>InvalidAccessError</code>: <code>code</code> is not 1000 nor is in the range 3000 to 4999.
* <code>SyntaxError</code>: UTF-8-encoded <code>reason</code> is longer than 123 bytes.

Note:
* If <code>ws.readyState</code> is <code>OPEN</code> or <code>CONNECTING</code>, <code>ws.readyState</code> is set to <code>CLOSING</code> and the closing handshake starts.
* If <code>ws.readyState</code> is <code>CLOSING</code> or <code>CLOSED</code>, nothing happens (because the closing handshake has already started).
|-
| rowspan="4" |[Event](/source/Event_(computing))
|<code>ws.'''onopen''' = (event) => {}</code>
<code>ws.addEventListener('''"open"''', (event) => {})</code>
|'''Opening handshake succeeded'''. <code>event</code> type is <code>Event</code>.
|-
|<code>ws.'''onmessage''' = (event) => {}</code>
<code>{{nowrap|ws.addEventListener('''"message"''', (event) <nowiki>=></nowiki>  {})}}</code>
|'''Data message received.''' <code>event</code> type is <code>MessageEvent</code>. This event is only fired if <code>ws.readyState</code> is <code>OPEN</code>.<ref>{{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 WebSockets|at=sec. 4.}}</ref>
* <code>event.data</code> is the data received, of type:
** <code>string</code> for text.
** <code>Blob</code> or <code>ArrayBuffer</code> for binary (see <code>ws.binaryType</code>).
* <code>event.origin</code> is <code>ws.url</code> but only with the scheme, host, and port (if any).
|-
|<code>ws.'''onclose''' = (event) => {}</code>
<code>ws.addEventListener('''"close"''', (event) => {})</code>
|The underlying '''TCP connection closed'''. <code>event</code> type is <code>CloseEvent</code>.<ref name=":1">{{Cite web |title=When the WebSocket connection is closed; substep 3. |url=https://websockets.spec.whatwg.org/#closeWebSocket |website=WHATWG WebSockets|at=sec. 4.|access-date=2024-04-13 |archive-date=2023-03-12 |archive-url=https://web.archive.org/web/20230312232711/https://websockets.spec.whatwg.org/#closeWebSocket |url-status=live }}</ref><ref name=":2">{{Cite IETF|rfc=6455|title=The WebSocket Connection is Closed|section=7.1.4}}</ref><ref>{{Cite IETF|rfc=6455|title=The WebSocket Connection Close Code|section=7.1.5}}</ref><ref>{{Cite IETF|rfc=6455|title=The WebSocket Connection Close Reason|section=7.1.6}}</ref>

* <code>event.code</code>: [status code](/source/WebSocket) (integer).
* <code>event.reason</code>: reason for closing (string).
* <code>event.wasClean</code>: <code>true</code> if the TCP connection was closed after the closing handshake was completed, else <code>false</code>.
Note:

* If the received ''Close'' frame contains a '''payload''', <code>event.code</code> and <code>event.reason</code> get their value from the payload.

* If the received ''Close'' frame contains '''no payload''', <code>event.code</code> is 1005 (''No code received'') and <code>event.reason</code> is an empty string.

* If '''no ''Close'' frame''' was received, <code>event.code</code> is 1006 (''Connection closed abnormally'') and <code>event.reason</code> is an empty string.
|-
|<code>ws.'''onerror''' = (event) => {}</code>
<code>ws.addEventListener('''"error"''', (event) => {})</code>
|'''Connection closed due to error'''. <code>event</code> type is <code>Event</code>.
|-
|[Attribute](/source/Attribute_(computing))
|<code>ws.'''binaryType'''</code> (string)
|'''Type of <code>event.data</code> in <code>ws.onmessage</code>''' when a binary data message is received. Initially set to <code>"blob"</code> (<code>Blob</code> object). May be changed to <code>"arraybuffer"</code> (<code>ArrayBuffer</code> object).<ref>{{Cite web|title=socket.binaryType|url=https://websockets.spec.whatwg.org/#:~:text=socket.binaryType|website=WHATWG WebSockets|at=sec. 3.1.}}</ref>
|-
| rowspan="5" |Read-only attribute
|<code>ws.'''url'''</code> (string)
|'''URL given to the <code>WebSocket</code> constructor''' with the following transformations:
* If scheme is <code>http</code> or <code>https</code>, change it to <code>ws</code> or <code>wss</code> respectively.
|-
|<code>ws.'''bufferedAmount'''</code> (number)
|'''Number of bytes''' of application data (UTF-8 text and binary data) that have been '''queued using <code>ws.send()</code> 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 <code>ws.send()</code>, and never reset to zero.<ref>{{Cite web|title=socket.bufferedAmount|url=https://websockets.spec.whatwg.org/#:~:text=socket.bufferedAmount|website=WHATWG WebSockets|at=sec. 3.1.}}</ref>
|-
|<code>ws.'''protocol'''</code> (string)
|'''Protocol accepted by the server''', or an empty string if <code>protocols</code> was not specified in the <code>WebSocket</code> constructor.
|-
|<code>ws.'''extensions'''</code> (string)
|'''Extensions accepted by the server'''.
|-
|<code>ws.'''readyState'''</code> (number)
|'''Connection state'''. It is one of the constants below. Initially set to <code>CONNECTING</code>.<ref>{{Cite web|title=ready state|url=https://websockets.spec.whatwg.org/#websocket-ready-state|website=WHATWG WebSockets|at=sec. 3.1.}}</ref>
|-
| rowspan="4" |[Constant](/source/Constant_(computer_programming))
|<code>WebSocket.'''CONNECTING''' = 0</code>
|'''Opening handshake is currently in progress'''. The initial state of the connection.<ref>{{Cite web |title=CONNECTING |url=https://websockets.spec.whatwg.org/#ref-for-dom-websocket-connecting%E2%91%A0 |website=WHATWG WebSockets|at=sec. 3.1.|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 }}</ref><ref>{{Cite IETF|rfc=6455|title=Client Requirements|section=4.1|page=14}}</ref>
|-
|<code>WebSocket.'''OPEN''' = 1</code>
|'''Opening handshake succeeded'''. The client and server may send messages to each other.<ref>{{Cite web |title=OPEN |url=https://websockets.spec.whatwg.org/#dom-websocket-open |website=WHATWG WebSockets|at=sec. 3.1.|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 }}</ref><ref>{{Cite IETF|rfc=6455|title=_The WebSocket Connection is Established_|page=20}}</ref>
|-
|<code>WebSocket.'''CLOSING''' = 2</code>
|'''Closing handshake is currently in progress'''. Either <code>ws.close()</code> was called or a ''Close'' message was received.<ref>{{Cite web |title=CLOSING |url=https://websockets.spec.whatwg.org/#dom-websocket-closing |website=WHATWG WebSockets|at=sec. 3.1.|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-closing |url-status=live }}</ref><ref>{{Cite IETF|rfc=6455|title=The WebSocket Closing Handshake is Started|section=7.1.3}}</ref>
|-
|<code>WebSocket.'''CLOSED''' = 3</code>
|The underlying '''TCP connection is closed'''.<ref>{{Cite web|title=CLOSED|url=https://websockets.spec.whatwg.org/#dom-websocket-closed|website=WHATWG WebSockets|at=sec. 3.1.|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}}</ref><ref name=":1" /><ref name=":2" />
|}

== Protocol ==
thumb|A diagram describing a connection using WebSocket
Steps:
# '''[Opening handshake](/source/WebSocket)''': [HTTP request](/source/HTTP) and [HTTP response](/source/HTTP).
# '''[Frame-based message](/source/WebSocket)''' exchange: data, ping and pong messages.
# '''[Closing handshake](/source/WebSocket)''': close message (request then echoed in response).

=== Opening handshake ===
The client sends an '''HTTP request''' ('''[method](/source/HTTP)''' '''GET''', '''[version](/source/HTTP) ≥ 1.1''') and the server returns an '''HTTP response''' with '''[status code 101](/source/List_of_HTTP_status_codes)''' (''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.<ref>{{Cite IETF|title=Opening Handshake|rfc=6455|section=1.3}}</ref><ref name="rfc-opening-handshake">{{Cite IETF|title=Protocol Overview|section=1.2|rfc=6455}}</ref>

{|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](/source/List_of_HTTP_header_fields)<ref>{{Cite IETF|rfc=6455|page=18|title=Client requirement 8..}}</ref>
|{{Varies}}
|{{yes|Yes (for browser clients)}}
|-
|[Host](/source/List_of_HTTP_header_fields)<ref>{{Cite IETF|rfc=6455|page=17|title=Client requirement 4..}}</ref>
|{{Varies}}
|rowspan="6" {{Yes}}
|-
|Sec-WebSocket-Version<ref>{{Cite IETF|rfc=6455|title=Client requirement 9..|page=18}}</ref>
|''13''
|-
|Sec-WebSocket-Key<ref>{{Cite IETF|rfc=6455|page=18|title=Client requirement 7..}}</ref>
|[base64](/source/base64)-encode(16 random bytes)
|-
| {{verth|Response}}
|Sec-WebSocket-Accept<ref>{{Cite IETF|rfc=6455|title=Server step 5.4..|page=24}}</ref>
|base64-encode([SHA1](/source/SHA1)(Sec-WebSocket-Key + {{nowrap|"[''258EAFA5-E914-47DA-95CA-C5AB0DC85B11''](/source/Magic_number_(programming))"}})){{efn|The plus sign represents '''[string concatenation](/source/string_concatenation)'''.}}
|-
|rowspan="4" {{verth|Both|va=middle}}
|[Connection](/source/List_of_HTTP_header_fields)<ref>{{Cite IETF|rfc=6455|title=Client requirement 6..|page=18}}</ref><ref>{{Cite IETF|rfc=6455|title=Server step 5.3.|page=24}}</ref>
|''Upgrade''
|-
|[Upgrade](/source/HTTP%2F1.1_Upgrade_header)<ref>{{Cite IETF|rfc=6455|title=Client requirement 5..|page=17}}</ref><ref>{{Cite IETF|rfc=6455|title=Server step 5.2.|page=24}}</ref>
|''websocket''
|-
|Sec-WebSocket-Protocol<ref>{{Cite IETF|rfc=6455|title=Client requirement 10..|page=18}}</ref>
|The request may contain a comma-separated list of strings (ordered by preference) indicating [application-level protocols](/source/Application_layer) (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<ref>{{Cite IETF|rfc=6455|title=Client requirement 11..|page=19}}</ref><ref>{{Cite IETF|rfc=6455|title=Sec-WebSocket-Extensions|section=11.3.2}}</ref><ref>{{Cite IETF|rfc=6455|title=Extensions|section=9}}</ref><ref>{{Cite IETF|rfc=6455|title=Negotiating Extensions|section=9.1}}</ref>
|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:<ref name="rfc-opening-handshake" />

<syntaxhighlight lang="http">
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
</syntaxhighlight>

Example response:<ref name="rfc-opening-handshake" />

<syntaxhighlight lang="http">
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat
</syntaxhighlight>

The following [Python](/source/Python_(programming_language)) code generates a random <code>Sec-WebSocket-Key</code>.
<syntaxhighlight lang="python3">
import base64
import os

print(base64.b64encode(os.urandom(16)))
</syntaxhighlight>

The following Python code calculates <code>Sec-WebSocket-Accept</code> using <code>Sec-WebSocket-Key</code> from the example request above.
<syntaxhighlight lang="python3">
import base64
import hashlib

KEY: bytes = b"dGhlIHNhbXBsZSBub25jZQ=="
MAGIC: bytes = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
print(base64.b64encode(hashlib.sha1(KEY + MAGIC).digest()))
</syntaxhighlight>

<code>Sec-WebSocket-Key</code> and <code>Sec-WebSocket-Accept</code> are intended to prevent a [caching](/source/Cache_(computing)) [proxy](/source/HTTP_proxy) from re-sending a previous WebSocket conversation,<ref>{{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 }}</ref> and does not provide any authentication, privacy, or integrity.

Though some servers accept a short <code>Sec-WebSocket-Key</code>, 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 '''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.<ref>{{Cite IETF|section=5.4|rfc=6455|title=Fragmentation}}</ref> 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](/source/Payload_(computing))), but the protocol extension was never accepted.<ref>{{cite IETF|draft=draft-ietf-hybi-websocket-multiplexing|title=A Multiplexing Extension for WebSockets|author1=John A. Tamplin|author2=Takeshi Yoshino|publisher=[IETF](/source/Internet_Engineering_Task_Force)|year=2013}}</ref>

* An '''unfragmented message''' consists of one frame with '''<code>FIN = 1</code>''' and '''<code>opcode ≠ 0</code>'''.
* A '''fragmented message''' consists of one frame with '''<code>FIN = 0</code>''' and '''<code>opcode ≠ 0</code>''', followed by zero or more frames with '''<code>FIN = 0</code>''' and '''<code>opcode = 0</code>''', and terminated by one frame with '''<code>FIN = 1</code>''' and '''<code>opcode = 0</code>'''.

=== Frame structure ===

{| class="wikitable"
![Offset](/source/Offset_(computer_science))<br>(bits)
! colspan="2" |Field<ref>{{Cite IETF|rfc=6455|title=Base Framing Protocol|section=5.2}}</ref>
!Size<br>(bits)
!Description
|-
|0
| colspan="2" |FIN<ref>{{Cite IETF|rfc=6455|title=FIN|page=28}}</ref>
|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" {{n/a|'''Reserved. 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.<ref>{{Cite IETF|rfc=6455|title=RSV1, RSV2, RSV3|page=28}}</ref>}}
|-
|2
| colspan="2" |RSV2
|1
|-
|3
| colspan="2" |RSV3
|1
|-
| 4
| colspan="2" |[Opcode](/source/Operation_code)
|4
|See [opcodes](/source/WebSocket) below.
|-
|8
| colspan="2" |[Masked](/source/Data_masking)<ref>{{Cite IETF|rfc=6455|title=Mask|page=29}}</ref>
|1
|{{ulist|1='''1 = frame is masked''' (i.e. masking key is present and the payload has been [XOR](/source/XOR)ed with the masking key). |2='''0 = frame is not masked''' (i.e. masking key is not present).}} See [client-to-server masking](/source/WebSocket) below.
|-
|9
| colspan="2" |Payload length<ref name=":0">{{Cite IETF|rfc=6455|title=Payload length|page=29}}</ref>
|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](/source/Most_Significant_Bit) must be 0) are the payload length.}} [Endianness](/source/Endianness) is '''big-endian'''. [Signedness](/source/Signedness) is '''unsigned'''. The '''minimum''' number of bits must be used to encode the length.
|-
| rowspan="3" {{varies}}
| colspan="2" |Masking key<ref name="rfc-client-to-server-masking">{{Cite IETF|title=Client-to-Server Masking|section=5.3|rfc=6455}}</ref>
|0 or 32
|'''[Random nonce](/source/Random_nonce)'''. Present if the masked field is 1. The client generates a masking key for every masked frame.
|-
|rowspan="2"|Payload
|Extension data
|rowspan="2"|Payload length (bytes)
|{{n/a|'''Must be empty''' unless defined by an extension.}}
|-
|Application data
|{{Depends}} on the opcode
|}

==== Opcodes ====
{| class="wikitable"
! colspan="2" |Frame type<ref>{{Cite IETF|rfc=6455|title=frame-opcode|page=31}}</ref>
!Opcode<ref>{{Cite IETF|rfc=6455|title=Opcode|page=29}}</ref>
!Related
[Web API](/source/WebSocket)
!Description
!Purpose
!{{vertical header|Fragmentable}}
!Max. payload length (bytes)
|-
| colspan="2" align="center" |Continuation frame
|0
|
|Non-first frame of a fragmented message.
|Message fragmentation
|
|rowspan="4"|{{math|2<sup>63</sup> − 1}}{{efn|The specification only explicitly restricts control frames. Thus, all other frames are restricted by the protocol limit of 63 bits for payload length (as the most significant bit must be zero).}}
|-
| rowspan="3" |Non-control frame
|Text
|1
| rowspan="2" |<code>send()</code>, {{nowrap|<code>{{nowrap|onmessage}}</code>}}
|UTF-8-encoded text.
|rowspan="2"|Data message
|rowspan="3" {{Yes}}
|-
|Binary
|2
|Binary data.
|-
|
|3–7
|
|{{n/a|'''Reserved''' for further non-control frames. May be defined by an extension.<ref name="rfc-extensibility">{{Cite IETF|rfc=6455|title=Extensibility|section=5.8}}</ref>}}
|
|-
| rowspan="4" |Control frame<ref>{{Cite IETF|title=Control Frames|section=5.5|rfc=6455}}</ref>
|Close
|8
|<code>close()</code>, <code>onclose</code>
|{{anchor|Closing handshake}}The WebSocket '''closing handshake starts upon either sending or receiving a ''Close'' frame'''.<ref>{{Cite IETF|title=The WebSocket Closing Handshake is Started|section=7.1.3|rfc=6455}}</ref> It may prevent data loss by complementing the [TCP closing handshake](/source/Transmission_Control_Protocol).<ref>{{Cite IETF|title=Closing Handshake|section=1.4|rfc=6455}}</ref> No frame can be sent after sending a ''Close'' frame. If a ''Close'' frame is received and no prior ''Close'' frame was sent, a ''Close'' frame must be sent in response (typically echoing the status code received). 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.<ref>{{Cite IETF|title=Close|section=5.5.1|rfc=6455}}</ref>
|rowspan="4"|Protocol state
|rowspan="4" {{No}}
|rowspan="4"|125
|-
|Ping
|9
|
|rowspan="2"|{{nowrap|May be used for [latency](/source/Latency_(engineering)) measurement}}, [keepalive](/source/keepalive) and [heartbeat](/source/Heartbeat_(computing)). Both sides can '''send 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.<ref>{{Cite IETF|title=Ping|section=5.5.2|rfc=6455}}</ref><ref>{{Cite IETF|title=Pong|section=5.5.3|rfc=6455}}</ref><ref>{{cite web|title=Ping and Pong frames|website=WHATWG WebSockets|url=https://websockets.spec.whatwg.org/#ping-and-pong-frames}}</ref>
|-
|Pong
|10
|
|-
|
|11–15
|
|{{n/a|'''Reserved''' for further control frames. May be defined by an extension.<ref name="rfc-extensibility"/>}}
|}

==== Client-to-server masking ====
A '''client must mask''' all frames sent to the server. A '''server must not mask''' any frames sent to the client.<ref>{{Cite IETF|title=Overview|section=5.1|rfc=6455}}</ref> Frame masking applies '''XOR between the payload and the masking key'''. The following [pseudocode](/source/pseudocode) describes the algorithm used to both mask and unmask a frame.<ref name="rfc-client-to-server-masking" />
 '''for''' i '''from''' 0 '''to''' payload_length − 1
    payload[i] := payload[i] xor masking_key[i mod 4]

=== Status codes ===
{| class="wikitable"
!Range<ref>{{Cite IETF|section=7.4.2|rfc=6455|title=Reserved Status Code Ranges}}</ref>
!Allowed in<br>''Close'' frame
!Code
<ref>{{Cite IETF|section=7.4.1|rfc=6455|title=Defined Status Codes}}</ref>
!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](/source/Internet_Assigned_Numbers_Authority).
|-
|4000–4999
|
|Private use.
|}

=== Compression extension ===
The <code>permessage-deflate</code> extension allows data messages to be compressed using the [DEFLATE](/source/DEFLATE) algorithm.
For example, during the opening handshake, the client and server may use the following header to enable the extension. The <code>RSV1</code> field of the first frame of a data message must be set to indicate the payload data is compressed.<ref>{{Cite IETF|rfc=7692|title= Compression Extensions for WebSocket}}</ref>
<syntaxhighlight lang="http">Sec-WebSocket-Extensions: permessage-deflate</syntaxhighlight>

=== Server implementation example ===
In Python.

Note: <code>recv()</code> returns up to the amount of bytes requested. For readability, the code ignores that, thus it may fail in non-ideal network conditions.
<syntaxhighlight lang="python3">
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 <= 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__ == "__main__":
    # Accept TCP connection on any interface at port 80
    ws: Socket = Socket()
    ws.bind(("", 80))
    ws.listen()
    
    handle_websocket_connection(ws)
</syntaxhighlight>

== Browser support ==
A secure version of the WebSocket protocol is implemented in Firefox 6,<ref>{{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 }}</ref> Safari 6, Google Chrome 14,<ref>{{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 }}</ref> [Opera](/source/Opera_(web_browser)) 12.10 and [Internet Explorer](/source/Internet_Explorer) 10.<ref>{{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 }}</ref>  A detailed protocol test suite report<ref name="autobahn">{{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 }}</ref> 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](/source/Safari_(web_browser)) 5, as well as the mobile version of Safari in [iOS 4.2](/source/iOS_4.2).<ref>{{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 }}</ref> The BlackBerry Browser in OS7 implements WebSockets.<ref>{{cite web|title=Web Sockets API |url=http://docs.blackberry.com/en/developers/deliverables/29271/Web_Sockets_support_1582781_11.jsp |publisher=[BlackBerry](/source/BlackBerry_Limited) |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 }}</ref> Because of vulnerabilities, it was disabled in Firefox 4 and 5,<ref>{{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 }}</ref> and Opera 11.<ref>{{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}}</ref>
Using browser developer tools, developers can inspect the WebSocket handshake as well as the WebSocket frames.<ref>{{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 }}</ref>

{| class="wikitable" style="text-align:right"
! Protocol version
! Draft date
! Internet Explorer
! Firefox<ref>{{cite web |url=https://developer.mozilla.org/en/WebSockets |title=WebSockets (support in Firefox) |publisher=Mozilla Foundation |website=developer.mozilla.org |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 }}</ref><br/>(PC)
! Firefox<br/>(Android)
! Chrome<br/>(PC, Mobile)
! Safari<br/>(Mac, iOS)
! Opera<br/>(PC, Mobile)
! 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]<br />[https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00 hybi-00]
| May 6, 2010<br />May 23, 2010
|
| 4.0<br/>(disabled)
|
| 6
| 5.0.1
| 11.00<br/>(disabled)
|
|-
! [https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07 hybi-07], v7
| April 22, 2011
|
| 6<ref>{{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 }}</ref>{{Efn|name="mozwebsocket"|Gecko-based browsers versions 6–10 implement the WebSocket object as "MozWebSocket",<ref>{{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 }}</ref> 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<ref>{{cite web|url=https://bugzilla.mozilla.org/show_bug.cgi?id=640003#c91|title=Bug 640003 - WebSockets - upgrade to ietf-07(comment 91)|publisher=Mozilla Foundation|date=2011-07-22|access-date=2011-07-28|archive-date=2021-04-01|archive-url=https://web.archive.org/web/20210401044535/https://bugzilla.mozilla.org/show_bug.cgi?id=640003#c91|url-status=live}}</ref>{{Efn|name="mozwebsocket"}}
| 7
| 14<ref>{{cite web |url=https://code.google.com/p/chromium/issues/detail?id=64470 |title=Chromium bug 64470 |website=code.google.com |date=2010-11-25 |access-date=2011-12-10 |archive-date=2015-12-31 |archive-url=https://web.archive.org/web/20151231184436/https://code.google.com/p/chromium/issues/detail?id=64470 |url-status=live }}</ref>
|
|
|
|-
! {{IETF RFC|6455}}, v13
| December, 2011
| 10<ref>{{cite web |url=https://blogs.msdn.com/b/ie/archive/2012/03/19/websockets-in-windows-consumer-preview.aspx |title=WebSockets in Windows Consumer Preview |publisher=Microsoft |work=IE Engineering Team |date=2012-03-19 |access-date=2012-07-23 |archive-date=2015-09-06 |archive-url=https://web.archive.org/web/20150906135037/http://blogs.msdn.com/b/ie/archive/2012/03/19/websockets-in-windows-consumer-preview.aspx |url-status=live }}</ref>
| 11
| 11
| 16<ref>{{cite web |url=https://trac.webkit.org/changeset/97249 |title=WebKit Changeset 97247: WebSocket: Update WebSocket protocol to hybi-17 |website=trac.webkit.org |access-date=2011-12-10 |archive-date=2012-01-05 |archive-url=https://web.archive.org/web/20120105121750/http://trac.webkit.org/changeset/97249 |url-status=live }}</ref>
| 6
| 12.10<ref>{{cite web|url=http://my.opera.com/ODIN/blog/2012/08/03/a-hot-opera-12-50-summer-time-snapshot |title=A hot Opera 12.50 summer-time snapshot |publisher=Opera Developer News |date=2012-08-03 |access-date=2012-08-03|archive-url=https://web.archive.org/web/20120805234006/http://my.opera.com/ODIN/blog/2012/08/03/a-hot-opera-12-50-summer-time-snapshot|archive-date=2012-08-05}}</ref>
| 4.4
|}

== Server implementations ==

* [Nginx](/source/Nginx) has supported WebSockets since 2013, implemented in version 1.3.13<ref>{{cite web |url=http://nginx.org/en/CHANGES |title=Welcome to nginx! |website=nginx.org |access-date=3 February 2022 |archive-url=https://web.archive.org/web/20120717224952/http://nginx.org/en/CHANGES|archive-date=17 July 2012|url-status=dead}}</ref> including acting as a [reverse proxy](/source/reverse_proxy) and [load balancer](/source/Load_balancing_(computing)) of WebSocket applications.<ref>{{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}}</ref>

* [Apache HTTP Server](/source/Apache_HTTP_Server) has supported WebSockets since July, 2013, implemented in version 2.4.5<ref>{{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}}</ref><ref>{{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}}</ref>
* [Internet Information Services](/source/Internet_Information_Services) added support for WebSockets in version 8 which was released with [Windows Server 2012](/source/Windows_Server_2012).<ref>{{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 }}</ref>
* [lighttpd](/source/lighttpd) has supported WebSockets since 2017, implemented in lighttpd 1.4.46.<ref>{{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 }}</ref>  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](/source/JSON) format, to a backend application.  lighttpd supports WebSockets over HTTP/2 since 2022, implemented in lighttpd 1.4.65.<ref>{{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 }}</ref>
* [https://mosquitto.org/ Eclipse Mosquitto] This is an [MQTT broker](/source/MQTT), but it supports the MQTT over WebSocket. So, it can be considered a type of WebSocket implementation.

ASP.NET Core have support for WebSockets using the {{Code|app.UseWebSockets();}} middleware.<ref>{{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}}</ref>

== Security considerations ==
Unlike regular cross-domain HTTP requests, WebSocket requests are not restricted by the [same-origin policy](/source/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](/source/cross-site_request_forgery)), which might be possible when the connection is authenticated with [cookies](/source/HTTP_cookie) 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.<ref>{{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 }}</ref> A live example of vulnerability was seen in 2020 in the form of [Cable Haunt](/source/Cable_Haunt).

== Proxy traversal ==
WebSocket protocol client implementations try to detect whether the [user agent](/source/user_agent) is configured to use a proxy when connecting to destination host and port, and if it is, uses [HTTP CONNECT](/source/HTTP_tunnel) 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.<ref>{{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 }}</ref>

If an encrypted WebSocket connection is used, then the use of [Transport Layer Security](/source/Transport_Layer_Security) (TLS) in the WebSocket Secure connection ensures that an <code>HTTP CONNECT</code> 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 <code>HTTP CONNECT</code> 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](/source/Reverse_proxy) and gateways by including eight bytes of key data after the headers, but not advertising that data in a <code>Content-Length: 8</code> header.<ref>{{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 }}</ref> This data was not forwarded by all intermediates, which could lead to protocol failure. More recent drafts (e.g., hybi-09<ref>{{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 }}</ref>) put the key data in a <code>Sec-WebSocket-Key</code> header, solving this problem.

== See also ==

{{Div col|colwidth=22em}}
* [Comparison of WebSocket implementations](/source/Comparison_of_WebSocket_implementations)
* [Network socket](/source/Network_socket)
* [Push technology](/source/Push_technology)
* [XMLHttpRequest](/source/XMLHttpRequest)
* [Server-sent events](/source/Server-sent_events)
* [WebRTC](/source/WebRTC)
* [HTTP/2](/source/HTTP%2F2)
* [Internet protocol suite](/source/Internet_protocol_suite)
* [BOSH](/source/BOSH_(protocol))

{{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](/source/W3C_recommendation) specification of the API
* [http://www.w3.org/TR/websockets/ The WebSocket API] – W3C [Candidate Recommendation](/source/W3C_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}}

Category:Web standards
Category:Application layer protocols
Category:HTML5
Category:Internet terminology
Category:Network socket
Category:Real-time web
Category:Web development
Category:2011 in computing

---
Adapted from the Wikipedia article [WebSocket](https://en.wikipedia.org/wiki/WebSocket) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/WebSocket?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
