CodePark/ questions / WebSockets, SSE & polling
START PRACTICINGPRACTICE
Backend question · HTTP & API design › WebSockets, SSE & polling

Explain the WebSocket opening handshake shown here.

GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

A WebSocket starts as a normal HTTP/1.1 GET request, and the server switches it to the WebSocket protocol.

The client's request has these headers:

  • Upgrade: websocket and Connection: Upgrade. Because it looks like normal HTTP, it passes through normal ports and infrastructure.
  • Sec-WebSocket-Key: a random value in base64.
  • The protocol version, 13.

If the server agrees, it replies 101 Switching Protocols. It proves it understood the WebSocket protocol with the Sec-WebSocket-Accept header. The server builds it in three steps:

  • Append a fixed GUID from RFC 6455 to the key.
  • Take the SHA-1 hash.
  • Encode the hash in base64.

This is not security. It only protects against confused servers and caches that do not understand WebSockets.

After the 101, the TCP connection no longer carries HTTP. Both sides exchange WebSocket frames. The server should also check the Origin header, because browsers do not apply CORS to WebSockets.

  • It starts as an HTTP GET request with Upgrade headers.
  • The server replies 101 Switching Protocols.
  • Sec-WebSocket-Accept comes from the key, a fixed GUID and SHA-1.
  • After that, WebSocket frames travel over the same connection.
  • Check the Origin header, because CORS does not apply.