Understand WebSocket frame formatear
WebSocket frames tener un específico binary formatear con opcode, masking, y payload longitud. Aprender a decodificar y construct WebSocket frames.
- 1
A WebSocket frame starts with 2 bytes: FIN + RSV + opcode (1 byte), MASK + payload length (1 byte). Opcodes: 0x0 (continuation), 0x1 (text), 0x2 (binary), 0x8 (close), 0x9 (ping), 0xA (pong). Client-to-server frames must be masked (4-byte mask key + XOR'd payload). Payload length: 0-125 inline, 126 = 16-bit length follows, 127 = 64-bit length follows.
- 2 Codificador hexadecimal →
Codificar a WebSocket frame. For a text frame "Hello": FIN=1, opcode=1 → 0x81. MASK=1, length=5 → 0x85. Mask key (4 random bytes). Payload: each byte XOR'd with mask key cyclically. The server unmask by XOR'ing again.
- 3 Codificador Base64 →
Codificar binary WebSocket payloads as base64 for debugging. Binary frames (opcode 0x2) can contain any data — base64 makes it inspectable in text tools and logs.
Preguntas frecuentes
- Why must client frames be masked?
- Masking prevents cache poisoning attacks on intermediaries (proxies, caches) that might misinterpret WebSocket data as HTTP responses. The mask is a 4-byte key applied with XOR — the server unmasks to recover the original payload. Server-to-client frames are not masked.
- What are ping/pong frames for?
- They are heartbeat frames. The client or server sends a ping (opcode 0x9), and the other side must respond with a pong (opcode 0xA) with the same payload. This keeps the connection alive through idle timeouts and checks if the peer is responsive. Send pings every 30-60 seconds.