Back
+20 XP
Concept

WebSocket Handshake & Frame Parsing (RFC 6455)

WebSockets upgrade an HTTP connection into a full-duplex TCP channel. The server validates the handshake by concatenating `Sec-WebSocket-Key` with a magic UUID, hashing with SHA-1, and base64 encoding 🔌.

python
import hashlib, base64

# RFC 6455 Magic GUID constant:
MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

# Client sends this random 16-byte nonce:
client_key = "dGhlIHNhbXBsZSBub25jZQ=="

# Calculate server Sec-WebSocket-Accept token:
combined = (client_key + MAGIC_GUID).encode("utf-8")
accept_token = base64.b64encode(hashlib.sha1(combined).digest()).decode("utf-8")

print(f"Sec-WebSocket-Accept: {accept_token} 🔌")

# 41. WebSocket Handshake & Frame Parsing (RFC 6455) WebSockets upgrade an HTTP connection into a full-duplex TCP channel. The server validates the handshake by concatenating `Sec-WebSocket-Key` with a magic UUID, hashing with SHA-1, and base64 encoding 🔌. ```python import hashlib, base64 # RFC 6455 Magic GUID constant: MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" # Client sends this random 16-byte nonce: client_key = "dGhlIHNhbXBsZSBub25jZQ==" # Calculate server Sec-WebSocket-Accept token: combined = (client_key + MAGIC_GUID).encode("utf-8") accept_token = base64.b64encode(hashlib.sha1(combined).digest()).decode("utf-8") print(f"Sec-WebSocket-Accept: {accept_token} 🔌") ``` Once the handshake completes with status `HTTP/1.1 101 Switching Protocols`, both client and server can transmit lightweight binary frames without HTTP header overhead! 🔌 --- ### Question Why does the WebSocket protocol require the HTTP 101 Switching Protocols handshake? 🧠 - [ ] a. To upgrade an existing HTTP/1.1 TCP socket into a bi-directional binary frame stream 🔌 - [ ] b. To force the browser to restart - [ ] c. To compress HTML files - [ ] d. To clear user cookies --- ### Challenge Given `client_key = "x3JJHMbDL1EzLkh9GBhXDw=="`, compute the `Sec-WebSocket-Accept` token using `hashlib.sha1` and `base64.b64encode`. Print the string. 🎯 <details> <summary>Solution</summary> ```python import hashlib, base64 GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" client_key = "x3JJHMbDL1EzLkh9GBhXDw==" token = base64.b64encode(hashlib.sha1((client_key + GUID).encode()).digest()).decode() print(token) ``` </details>

Checkpoint

Why does the WebSocket protocol require the HTTP 101 Switching Protocols handshake? 🧠

Practice

Given `client_key = "x3JJHMbDL1EzLkh9GBhXDw=="`, compute the `Sec-WebSocket-Accept` token using `hashlib.sha1` and `base64.b64encode`. Print the string. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks