乐闻世界logo
搜索文章和话题

How does WebSocket handshake work in detail?

2月18日 21:43

WebSocket handshake is a process of upgrading from HTTP protocol to WebSocket protocol, implemented through HTTP Upgrade mechanism.

Detailed Handshake Process

1. Client Initiates Handshake Request

Client sends a special HTTP GET request with the following key header fields:

shell
GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13 Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

Key Headers Explanation:

  • Upgrade: websocket: Tells server client wants to upgrade to WebSocket protocol
  • Connection: Upgrade: Indicates this is an upgrade connection
  • Sec-WebSocket-Key: Random string generated by client for server verification
  • Sec-WebSocket-Version: WebSocket protocol version, currently 13
  • Sec-WebSocket-Protocol: Optional, specifies sub-protocol
  • Sec-WebSocket-Extensions: Optional, specifies extension features

2. Server Verifies and Responds

After receiving request, server performs following verification:

  1. Verify Sec-WebSocket-Key exists
  2. Concatenate Sec-WebSocket-Key with GUID 258EAFA5-E914-47DA-95CA-C5AB0DC85B11
  3. Perform SHA-1 hash on concatenated string
  4. Base64 encode the hash result
  5. Put encoded result in Sec-WebSocket-Accept header

Server response:

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

3. Connection Successfully Established

After server returns 101 status code, HTTP connection upgrades to WebSocket connection, both parties start communicating using WebSocket data frames.

Handshake Security

Preventing Cross-Site WebSocket Hijacking (CSWSH)

  • Origin header verification: Server checks request source
  • Sec-WebSocket-Key verification: Prevents cache poisoning attacks

Best Practices

  • Use WSS (WebSocket Secure) encrypted connections
  • Verify Origin header
  • Implement proper authentication mechanisms
  • Limit connection frequency
标签:WebSocket