What is WebSockets Frame?

Technology CommunityCategory: WebSocketsWhat is WebSockets Frame?
VietMX Staff asked 3 years ago

Websocket is not a stream based protocol like TCP, it’s message based. The websocket protocol communicates with frames. Frames are a header + application data. The frame header contains information about the frame and the application data. The application data is any and all stuff you send in the frame “body”.

In its most basic form the websocket protocol has three non-control frames and three control frames. These are

  • Non-control:
    • ‘text’ – denotes we are sending ‘utf-8’ encoded bytes
    • ‘binary’ – denotes we are sending raw bytes
    • ‘continue’ – denotes this message is a continuation fragment of the previous message.
  • Control:
    • ‘close’ – says we either want to close, or are responding to a close
    • ‘ping’ – pings!
    • ‘pong’ – pongs!

A frame looks like this:

 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 ...                |
+---------------------------------------------------------------+