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

What is the WebSocket handshake process?

2月18日 19:06

WebSocket connection establishment is completed through HTTP upgrade request, the process is as follows:

Client Initiates Handshake

Client sends an HTTP GET request with the following key headers:

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

Key Headers Explanation:

  • Upgrade: websocket - Request to upgrade to WebSocket protocol
  • Connection: Upgrade - Indicates this is an upgrade request
  • Sec-WebSocket-Key - Random string generated by client for security verification
  • Sec-WebSocket-Version - WebSocket protocol version, currently 13
  • Origin - Request source, used for security verification

Server Responds to Handshake

After verifying the request, server returns 101 status code:

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

Sec-WebSocket-Accept Calculation Process:

  1. Concatenate client's Sec-WebSocket-Key with fixed string 258EAFA5-E914-47DA-95CA-C5AB0DC85B11
  2. Perform SHA-1 hash on the concatenated string
  3. Base64 encode the hash result
  4. Use the obtained value as Sec-WebSocket-Accept to return

Connection Established

After successful handshake, TCP connection upgrades to WebSocket connection, both parties can start bidirectional communication.

Security Considerations

  1. Origin Verification: Server should verify Origin header to prevent CSRF attacks
  2. Key Verification: Ensure request comes from genuine WebSocket client through Sec-WebSocket-Key
  3. WSS Protocol: Use wss:// (WebSocket Secure) for encrypted communication
标签:WebSocket