Tech
• 1 min read

How HTTP works with WebSocket


How HTTP works with WebSocket

WebSockets uses HTTP 1.1, but it’s stateful.

It began with an HTTP request and then upgraded to a WebSocket connection, which is full-duplex and bidirectional.

WebSocket Handshake:

  1. Initiation: Client handshake request:

The client sends an HTTP GET request with the following headers

  • Upgrade: websocket: Indicates that the client wants to upgrade to a WebSocket connection.
  • Connection: Upgrade: Signals that the connection should be upgraded.
  • Sec-WebSocket-Key: A base64-encoded random value (16 bytes) that is used to prove that the server supports WebSockets.
  • Sec-WebSocket-Version: Specifies the WebSocket protocol version (usually 13).
  1. Server Handshake
//Example:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

If the server accepts the WebSocket upgrade request, it responds with an HTTP 101 status code and the following headers:

  • Upgrade: websocket: Confirms the upgrade to WebSocket.
  • Connection: Upgrade: Confirms the connection upgrade.
  • Sec-WebSocket-Accept: A value derived from the client’s Sec-WebSocket-Key to prove that the server supports WebSockets.
    • The server concatenates the client’s Sec-WebSocket-Key with a fixed GUID (258EAFA5-E914-47DA-95CA-C5AB0DC85B11), computes the SHA-1 hash of the result, and returns the base64-encoded hash.
    • The server must respond with 101 Switching Protocols to confirm the upgrade.
// Example
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
  1. Connection Upgrade

Once the handshake is complete:

  • The underlying TCP connection remains open.
  • The protocol switches from HTTP to WebSocket.
  • Both the client and server can send WebSocket frames (data messages) to each other.