Skip to content
WebSocket Frame Format
step 1/5

Reading — step 1 of 5

Read

~2 min readFrame Format

WebSocket Frame Format

After the handshake, every message is a series of FRAMES:

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len |    Extended payload length    |
|I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
|N|V|V|V|       |S|             |   (if payload len==126/127)   |
| |1|2|3|       |K|             |                               |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
|     Extended payload length continued, if payload len == 127  |
+ - - - - - - - - - - - - - - - +-------------------------------+
|                               |Masking-key, if MASK set to 1  |
+-------------------------------+-------------------------------+
| Masking-key (continued)       |          Payload Data         |
+-------------------------------- - - - - - - - - - - - - - - - +
:                     Payload Data continued ...                :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
|                     Payload Data continued ...                |
+---------------------------------------------------------------+

Key fields:

  • FIN (1 bit): 1 = last frame of message; 0 = more frames follow
  • opcode (4 bits):
    • 0x0 continuation
    • 0x1 text (UTF-8)
    • 0x2 binary
    • 0x8 close
    • 0x9 ping
    • 0xA pong
  • MASK (1 bit): 1 if frame is masked (REQUIRED for client→server frames)
  • Payload len (7 bits):
    • 0-125: actual length
    • 126: next 16 bits are length
    • 127: next 64 bits are length

So small frames have a 2-byte header. Large frames have a 4 or 10-byte header.

Why mask? Defends against cache poisoning attacks on intermediate proxies. Server→client frames are NOT masked (no equivalent attack vector).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…