Mercurial
annotate mrjunejune/src/blog/websocket-demystified/index.md @ 132:7a63e41a21fb
[Seobeo] Added debug targets.
| author | June Park <parkjune1995@gmail.com> |
|---|---|
| date | Fri, 09 Jan 2026 08:23:54 -0800 |
| parents | b230a743a01e |
| children | 902e29c38d66 |
| rev | line source |
|---|---|
| 130 | 1 # WebSocket Demystified |
| 2 | |
| 3 WebSockets have been around for more than 10 years now—the [RFC 6455](https://www.rfc-editor.org/rfc/rfc6455) was dropped way back in 2011. This was inevitable. As apps got more complex, people wanted real bidirectional communication without resorting to hacky solutions like raw TCP connections with custom keys or the constant overhead of short/long polling. | |
| 4 | |
| 5 Today, it’s the standard for everything from chat apps to LLM interfaces, where the model streams bytes back to you one token at a time as it predicts the next word. | |
| 6 | |
|
132
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
7 Most developers just grab a library like [ws](https://github.com/websockets/ws) for Node.js or [websockets](https://websockets.readthedocs.io/) for Python and call it a day. But many don’t realize the underlying mechanism is actually pretty simple to implement yourself in a day or so. Also they misunderstand what websocket actually do. Let's look at how to build it from scratch and debunk myths. |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
8 |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
9 ### The "65,535" Myth |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
10 |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
11 Before we write a single line of code, Let's talk about common myth. You’ll often hear developers say, *"A server can only handle 65,535 WebSocket connections because there are only 65,535 ports."* |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
12 |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
13 If this were true, Discord or Slack would need millions of separate IP addresses just to function. The confusion comes from the 16-bit size of the TCP port field, but a connection isn't defined by a port alone. You will see in this blog. |
| 130 | 14 |
| 15 --- | |
| 16 | |
| 17 ## Requirements | |
| 18 | |
| 19 * Ability to type | |
|
132
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
20 * Half a brain to real mechanics, not the surface-level myths. |
| 130 | 21 * A computer |
| 22 | |
| 23 --- | |
| 24 | |
| 25 ## The Lifecycle | |
| 26 | |
| 27 To get a WebSocket up and running, you have to follow a specific dance. It’s not just "connecting to a port"; it's an evolution of an existing relationship. | |
| 28 | |
| 29 1. **The Handshake:** A client sends a "pretty please" HTTP request asking to upgrade the connection. | |
| 30 2. **The Response:** The server agrees (101 Switching Protocols) and sends back a specific hash. | |
| 31 3. **The Switch:** Both sides stop talking "HTTP" and start talking "Frames." | |
| 32 4. **The Interaction:** Bidirectional, binary-framed messaging until someone closes the door. | |
| 33 | |
| 34 --- | |
| 35 | |
| 36 ## Opening Handshakes | |
| 37 | |
| 38 To start the upgrade from HTTP to WebSocket, the client sends a standard GET request but with some very specific headers. | |
| 39 | |
|
132
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
40 <div class="center"> <img src="/public/web-socket-header.webp" /> </div> |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
41 |
| 131 | 42 |
| 130 | 43 I’m assuming you know how HTTP works. If not, you can open a developer tool by right clicking on your browser and seeing into network tab and refershign the page. The only interesting values here is the `Sec-WebSocket-Key`. This key is usually a 16-byte random value encoded in **Base64**. |
| 44 | |
| 131 | 45 **Note:** It’s not for security—it’s to prevent intermediate caches from accidentally serving a cached WebSocket response to a different client. |
| 130 | 46 |
| 47 But before we jump into that, we need to construct that Base64 key. | |
| 48 | |
| 49 ### What is Base64? | |
| 50 | |
| 51 Let's ask Gemini: | |
| 52 | |
| 53 > "Base64 is a binary-to-text encoding scheme that represents data in an ASCII string format by translating it into a radix-64 representation, using a specific set of 64 printable characters." — Gemini | |
| 54 | |
| 131 | 55 |
| 130 | 56 Nice, it didn't halluciante. Let's constracut these. Here they are 64 characters that are safe to print in ASCII.: |
| 57 | |
| 58 ```c | |
| 59 static const char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
| 60 | |
| 61 ``` | |
| 62 | |
| 63 In Python, this is a one-liner: | |
| 64 | |
| 65 ```python | |
| 66 import base64 | |
| 67 import os | |
| 68 print(base64.b64encode(os.urandom(16))) | |
| 69 | |
| 70 ``` | |
| 71 | |
| 72 But we are rewriting this from scratch in **C**, so we need to suffer a little. The logic is: take 3 bytes (24 bits) and split them into 4 chunks of 6 bits each. Each 6-bit chunk becomes an index into our `base64_chars` array. | |
| 73 | |
| 74 #### Step 1: Generate Random Bytes | |
| 75 | |
| 76 First, we grab 16 random bytes. | |
| 77 | |
| 78 ```c | |
| 79 srand((unsigned int)time(NULL)); | |
| 80 uint8 random_value[16]; | |
| 81 | |
| 82 for (int i = 0; i < 16; i++) | |
| 83 random_value[i] = (uint8)(rand() % 256); | |
| 84 ``` | |
| 85 | |
| 86 #### Step 2: The Bit-Shifting Magic | |
| 87 | |
| 88 We loop through our 16 bytes in groups of 3. We pack them into a 32-bit integer, then carve that integer into 6-bit slices. | |
| 89 | |
| 90 > **Note:** The length isn't strictly defined as 32, but many implementations land there. | |
| 91 | |
| 92 ```c | |
| 93 char result[32] = {0}; | |
| 94 int32 result_index = 0; | |
| 95 | |
| 96 for (int i = 0; i < 16; i += 3) { | |
| 97 uint32 first_value = 0, second_value = 0, third_value = 0; | |
| 98 | |
| 99 if (i < 15) { | |
| 100 first_value = (uint32)random_value[i] << 16; | |
| 101 second_value = (uint32)random_value[i+1] << 8; // Fixed logic from original draft | |
| 102 third_value = (uint32)random_value[i+2]; | |
| 103 } else { | |
| 104 // Handle the trailing bytes (padding logic usually goes here) | |
| 105 first_value = (uint32)random_value[i] << 16; | |
| 106 } | |
| 107 | |
| 108 uint32 group_value = first_value | second_value | third_value; | |
| 109 | |
| 110 // Map bits to characters: 0x3F is 0011 1111 (keeps only 6 bits) | |
| 111 result[result_index++] = base64_chars[(group_value >> 18) & 0x3F]; | |
| 112 result[result_index++] = base64_chars[(group_value >> 12) & 0x3F]; | |
| 113 result[result_index++] = base64_chars[(group_value >> 6) & 0x3F]; | |
| 114 result[result_index++] = base64_chars[group_value & 0x3F]; | |
| 115 } | |
| 116 | |
| 117 ``` | |
| 118 | |
| 119 Now you have a `Sec-WebSocket-Key`. When the server gets it, it appends a "Magic String" (`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`), SHA1 hashes it, and Base64 encodes it back to you as `Sec-WebSocket-Accept`. | |
| 120 | |
| 121 --- | |
| 122 | |
| 123 ## Upgrading the Protocol | |
| 124 | |
| 125 If you are the client, you just wait for that `101 Switching Protocols` response. Once you see it, you stop sending HTTP text and start sending frames. | |
| 126 | |
| 127 If you are the **server**, you need to keep that connection alive. In my project, `Seobeo`, I create a separate connection object, throw away the HTTP request info to save memory, and start a fresh buffer for WebSocket frames. | |
| 128 | |
| 129 ```c | |
| 130 // Transitioning the state from HTTP to WebSocket | |
| 131 Seobeo_WebSocket_Server_Connection *p_conn = malloc(sizeof(Seobeo_WebSocket_Server_Connection)); | |
| 132 memset(p_conn, 0, sizeof(Seobeo_WebSocket_Server_Connection)); | |
| 133 | |
|
132
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
134 p_conn->p_handle = p_handle; // file descriptor |
| 130 | 135 p_conn->is_active = TRUE; |
| 136 p_conn->fragment_capacity = 4096; | |
| 137 p_conn->fragment_buffer = malloc(p_conn->fragment_capacity); | |
| 138 | |
| 139 ``` | |
| 140 | |
|
132
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
141 ### Wait, what is the p_handle or file descriptor here?? |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
142 |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
143 The File Descriptor (FD) is the internal ID badge your server assigns to a connection. The OS identifies a unique connection via a 4-tuple; Source IP, Source Port, Destination IP, Destination Port. You can think of the OS as a giant hashmap that links these 4-tuples to an integer (the FD). |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
144 |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
145 So the limits are from the number of FD and RAM capactiy. You can check your system's FD limit with: |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
146 |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
147 ```bash |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
148 ulimit -n |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
149 ``` |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
150 |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
151 Now, we have debunked this myth. Let's see how the protocol actually works. |
|
7a63e41a21fb
[Seobeo] Added debug targets.
June Park <parkjune1995@gmail.com>
parents:
131
diff
changeset
|
152 |
| 130 | 153 --- |
| 154 | |
| 155 ## Frame-Based Protocols | |
| 156 | |
| 157 This is where the logic gets "cancerous." WebSockets don't just send raw strings; they wrap everything in a **Frame**. | |
| 158 | |
| 159 ### The Opcode Table | |
| 123 | 160 |
| 130 | 161 The first byte contains the `FIN` bit (is this the end of the message?) and the `Opcode` (what kind of data is this?). |
| 162 | |
| 163 | Opcode (Hex) | Meaning | Description | | |
| 164 | --- | --- | --- | | |
| 165 | `0x0` | Continuation | Part of a multi-frame message | | |
| 166 | `0x1` | Text | UTF-8 payload | | |
| 167 | `0x2` | Binary | Raw binary data | | |
| 168 | `0x8` | Close | Terminate the connection | | |
| 169 | `0x9` | Ping | Heartbeat check | | |
| 170 | `0xA` | Pong | Heartbeat response | | |
| 171 | |
| 172 ### The Masking Rule | |
| 173 | |
| 174 * **Client to Server:** MUST be masked. | |
| 175 * **Server to Client:** MUST NOT be masked. | |
| 176 If a client sends unmasked data, the server must close the connection. It’s the law. | |
| 177 | |
| 178 ### Why the Bitwise Mess? (Endianness) | |
| 179 | |
| 180 In the code below, you’ll see things like `payload_length >> 56`. This is because network protocol headers use **Big-Endian** (most significant byte first). If your computer is Little-Endian (most are), you have to manually shift bits into the right order so the wire sees them correctly. | |
| 181 | |
| 182 --- | |
| 183 | |
| 184 ## Sending a Frame (Client Side) | |
| 185 | |
| 186 Here is how we construct a frame to send data to the server. | |
| 187 | |
| 188 ```c | |
| 189 uint8 frame[14]; | |
| 190 size_t frame_len = 0; | |
| 191 | |
| 192 // Byte 0: FIN bit (0x80) and Opcode | |
| 193 frame[0] = (fin ? 0x80 : 0x00) | (opcode & 0x0F); | |
| 194 frame_len++; | |
| 195 | |
| 196 // Generate a 4-byte mask key | |
| 197 uint8 mask_key[4]; | |
| 198 for (int i = 0; i < 4; i++) | |
| 199 mask_key[i] = (uint8)(rand() % 256); | |
| 200 | |
| 201 // Byte 1+: Payload Length logic | |
| 202 if (payload_length < 126) { | |
| 203 frame[1] = 0x80 | (uint8)payload_length; // 0x80 sets the MASK bit | |
| 204 frame_len++; | |
| 205 } else if (payload_length <= 65535) { | |
| 206 frame[1] = 0x80 | 126; | |
| 207 frame[2] = (uint8)((payload_length >> 8) & 0xFF); | |
| 208 frame[3] = (uint8)(payload_length & 0xFF); | |
| 209 frame_len += 3; | |
| 210 } else { | |
| 211 frame[1] = 0x80 | 127; | |
| 212 for (int i = 0; i < 8; i++) | |
| 213 frame[2 + i] = (uint8)((payload_length >> (56 - i * 8)) & 0xFF); | |
| 214 frame_len += 9; | |
| 215 } | |
| 216 | |
| 217 // Attach the mask key | |
| 218 memcpy(frame + frame_len, mask_key, 4); | |
| 219 frame_len += 4; | |
| 220 | |
| 221 ``` | |
| 222 | |
| 223 To actually send the data, you XOR every byte with the mask: | |
| 224 | |
| 225 ```c | |
| 226 for (size_t i = 0; i < length; i++) | |
| 227 data[i] ^= mask_key[i % 4]; | |
| 123 | 228 |
| 130 | 229 ``` |
| 230 | |
| 231 --- | |
| 232 | |
| 233 ## Receiving a Frame (Server Side) | |
| 234 | |
| 235 On the server side, we have to do the reverse. We peel the onion layer by layer. | |
| 236 | |
| 237 #### 1. Parse the Header | |
| 238 | |
| 239 We check the first two bytes to see how big the payload is and if it's masked. | |
| 240 | |
| 241 ```c | |
| 242 uint8 *buf = p_conn->p_handle->read_buffer; | |
| 243 uint8 byte1 = buf[0]; | |
| 244 uint8 byte2 = buf[1]; | |
| 245 | |
| 246 boolean fin = (byte1 & 0x80) != 0; | |
| 247 Seobeo_WebSocket_Opcode opcode = (Seobeo_WebSocket_Opcode)(byte1 & 0x0F); | |
| 248 boolean masked = (byte2 & 0x80) != 0; | |
| 249 uint64 payload_len = byte2 & 0x7F; | |
| 250 | |
| 251 size_t header_len = 2; | |
| 252 | |
| 253 ``` | |
| 254 | |
| 255 #### 2. Handle Extended Lengths | |
| 256 | |
| 257 If the length is 126 or 127, it means the actual size is hidden in the next 2 or 8 bytes. | |
| 258 | |
| 259 ```c | |
| 260 if (payload_len == 126) { | |
| 261 payload_len = (buf[2] << 8) | buf[3]; | |
| 262 header_len += 2; | |
| 263 } else if (payload_len == 127) { | |
| 264 payload_len = 0; | |
| 265 for (int i = 0; i < 8; i++) | |
| 266 payload_len = (payload_len << 8) | buf[2 + i]; | |
| 267 header_len += 8; | |
| 268 } | |
| 269 | |
| 270 ``` | |
| 271 | |
| 272 #### 3. Unmask the Payload | |
| 273 | |
| 274 If the data is masked (and it should be if it's from a client), we use that 4-byte key to flip the bits back to normal. | |
| 275 | |
| 276 ```c | |
| 277 uint8 mask_key[4] = {0}; | |
| 278 if (masked) { | |
| 279 memcpy(mask_key, buf + header_len, 4); | |
| 280 header_len += 4; | |
| 281 } | |
| 282 | |
| 283 uint8 *payload = malloc(payload_len); | |
| 284 memcpy(payload, buf + header_len, payload_len); | |
| 285 | |
| 286 if (masked) | |
| 287 Seobeo_WebSocket_Unmask_Data(payload, payload_len, mask_key); | |
| 288 | |
| 289 ``` | |
| 290 | |
| 291 --- | |
| 292 | |
| 293 ## Conclusion | |
| 294 | |
| 295 That’s it. That is WebSockets in a nutshell. Once you handle the bit-shifting for the length and the XOR masking, you’re just reading and writing to a socket like any other protocol. | |
| 296 | |
| 297 You can test my implementation at `mrjunejune.com/talk`. Open two tabs and talk to yourself—it’s a great way to verify your frames are flying correctly. |