HTTP/2 WebSockets

Philip Jones
2 min readJan 25, 2019

--

HTTP/2 was standardized in 2015 without any mention of WebSockets. For most of the time since then I assumed that there would be no WebSockets over HTTP/2. That changed in September last year with the publication of RFC 8441, which will be supported in browsers in 2019 approximately 10 years after WebSockets were first introduced.

HTTP/2 WebSockets serve the same purpose as HTTP/1 WebSockets in that they provide a bi-direction data flow with minimal headers or framing i.e. WebSockets provide a more efficient method of continuous communication than is possible with HTTP. This makes WebSockets an ideal choice for games, chat applications and anything that requires real time updates.

The WebSocket connection itself is unchanged between HTTP/2 and HTTP/1 except that the WebSocket frames are wrapped in HTTP/2 data frames (providing the stream id and flags specific to HTTP/2). The only differences are in how the WebSocket connection is established.

In HTTP/1 a WebSocket is established via a handshake between the client and the server that ensured that the two parties agreed on the version, subprotocols, and extensions to be used. Critically the handshake also exchanged a key that was unique to the connection, in order to avoid any HTTP caching.

This handshake consisted of a HTTP GET request (from the client) being responded to with a 101, Switching Protocols, response (from the server). On completion the connection would then become a WebSocket and follow the WebSocket protocol. If anything went wrong the server can reply with any other type of response indicating the error.

In HTTP/2 a WebSocket is established via a similar process whereby a client sends a HTTP CONNECT request and the server responds with a 200 response whilst agreeing on the version, subprotocols and extensions to use. The first difference is that the key no longer needs to be exchanged as the :protocol pseudo header serves the same purpose. The second difference is that only a single stream is becomes the WebSocket rather than the entire connection thereby allowing HTTP/2 multiplexing to continue.

Users will likely never see these differences, nor will most developers as using HTTP/2 WebSockets requires no actions by either. Browsers will simply choose to use HTTP/2 WebSockets if the server advertises support. They should however notice the improved performance in general now that a single HTTP/2 connection can multiplex requests and WebSockets.

--

--

Philip Jones

Maintainer of Quart, Hypercorn and various other Python HTTP projects.