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:
httpGET /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 protocolConnection: Upgrade- Indicates this is an upgrade requestSec-WebSocket-Key- Random string generated by client for security verificationSec-WebSocket-Version- WebSocket protocol version, currently 13Origin- Request source, used for security verification
Server Responds to Handshake
After verifying the request, server returns 101 status code:
httpHTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Accept Calculation Process:
- Concatenate client's
Sec-WebSocket-Keywith fixed string258EAFA5-E914-47DA-95CA-C5AB0DC85B11 - Perform SHA-1 hash on the concatenated string
- Base64 encode the hash result
- Use the obtained value as
Sec-WebSocket-Acceptto return
Connection Established
After successful handshake, TCP connection upgrades to WebSocket connection, both parties can start bidirectional communication.
Security Considerations
- Origin Verification: Server should verify Origin header to prevent CSRF attacks
- Key Verification: Ensure request comes from genuine WebSocket client through Sec-WebSocket-Key
- WSS Protocol: Use
wss://(WebSocket Secure) for encrypted communication