Mercurial
comparison mrjunejune/src/blog/websocket-demystified/index.md @ 130:3a564ffb2092 websocket-blog
Wrote my blog.
| author | June Park <parkjune1995@gmail.com> |
|---|---|
| date | Fri, 09 Jan 2026 07:19:09 -0800 |
| parents | 3f4ec30e42e0 |
| children | b230a743a01e |
comparison
equal
deleted
inserted
replaced
| 123:3f4ec30e42e0 | 130:3a564ffb2092 |
|---|---|
| 1 # Websocket Demystified | 1 # WebSocket Demystified |
| 2 | 2 |
| 3 Websocket has been around for more than 10 years now. (Its [RFC](https://www.rfc-editor.org/rfc/rfc6455) was created in 2011.). This was inevitable as apps got more complexed people wanted to create an application that can create bidirectional communicate with server, and not create hacky solutions that will create raw TCP connection between client and server with some keys or do some short/long polling. Now, this is the most widely used protocol for LLM chat usages or any chat usages as expected since LLM sends messages in a stream of bytes as it is predicting next words at a time. Many developers create websocket connection through | 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 | 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 | |
| 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. Let's look at how to build it from scratch. | |
| 8 | |
| 9 --- | |
| 10 | |
| 11 ## Requirements | |
| 12 | |
| 13 * Ability to type | |
| 14 * Half a brain | |
| 15 * A computer | |
| 16 | |
| 17 --- | |
| 18 | |
| 19 ## The Lifecycle | |
| 20 | |
| 21 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. | |
| 22 | |
| 23 1. **The Handshake:** A client sends a "pretty please" HTTP request asking to upgrade the connection. | |
| 24 2. **The Response:** The server agrees (101 Switching Protocols) and sends back a specific hash. | |
| 25 3. **The Switch:** Both sides stop talking "HTTP" and start talking "Frames." | |
| 26 4. **The Interaction:** Bidirectional, binary-framed messaging until someone closes the door. | |
| 27 | |
| 28 --- | |
| 29 | |
| 30 ## Opening Handshakes | |
| 31 | |
| 32 To start the upgrade from HTTP to WebSocket, the client sends a standard GET request but with some very specific headers. | |
| 33 | |
| 34 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**. | |
| 35 | |
| 36 > **Note:** It’s not for security—it’s to prevent intermediate caches from accidentally serving a cached WebSocket response to a different client. | |
| 37 | |
| 38 But before we jump into that, we need to construct that Base64 key. | |
| 39 | |
| 40 ### What is Base64? | |
| 41 | |
| 42 Let's ask Gemini: | |
| 43 | |
| 44 > "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 | |
| 45 | |
| 46 Nice, it didn't halluciante. Let's constracut these. Here they are 64 characters that are safe to print in ASCII.: | |
| 47 | |
| 48 ```c | |
| 49 static const char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
| 50 | |
| 51 ``` | |
| 52 | |
| 53 In Python, this is a one-liner: | |
| 54 | |
| 55 ```python | |
| 56 import base64 | |
| 57 import os | |
| 58 print(base64.b64encode(os.urandom(16))) | |
| 59 | |
| 60 ``` | |
| 61 | |
| 62 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. | |
| 63 | |
| 64 #### Step 1: Generate Random Bytes | |
| 65 | |
| 66 First, we grab 16 random bytes. | |
| 67 | |
| 68 ```c | |
| 69 srand((unsigned int)time(NULL)); | |
| 70 uint8 random_value[16]; | |
| 71 | |
| 72 for (int i = 0; i < 16; i++) | |
| 73 random_value[i] = (uint8)(rand() % 256); | |
| 74 ``` | |
| 75 | |
| 76 #### Step 2: The Bit-Shifting Magic | |
| 77 | |
| 78 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. | |
| 79 | |
| 80 > **Note:** The length isn't strictly defined as 32, but many implementations land there. | |
| 81 | |
| 82 ```c | |
| 83 char result[32] = {0}; | |
| 84 int32 result_index = 0; | |
| 85 | |
| 86 for (int i = 0; i < 16; i += 3) { | |
| 87 uint32 first_value = 0, second_value = 0, third_value = 0; | |
| 88 | |
| 89 if (i < 15) { | |
| 90 first_value = (uint32)random_value[i] << 16; | |
| 91 second_value = (uint32)random_value[i+1] << 8; // Fixed logic from original draft | |
| 92 third_value = (uint32)random_value[i+2]; | |
| 93 } else { | |
| 94 // Handle the trailing bytes (padding logic usually goes here) | |
| 95 first_value = (uint32)random_value[i] << 16; | |
| 96 } | |
| 97 | |
| 98 uint32 group_value = first_value | second_value | third_value; | |
| 99 | |
| 100 // Map bits to characters: 0x3F is 0011 1111 (keeps only 6 bits) | |
| 101 result[result_index++] = base64_chars[(group_value >> 18) & 0x3F]; | |
| 102 result[result_index++] = base64_chars[(group_value >> 12) & 0x3F]; | |
| 103 result[result_index++] = base64_chars[(group_value >> 6) & 0x3F]; | |
| 104 result[result_index++] = base64_chars[group_value & 0x3F]; | |
| 105 } | |
| 106 | |
| 107 ``` | |
| 108 | |
| 109 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`. | |
| 110 | |
| 111 --- | |
| 112 | |
| 113 ## Upgrading the Protocol | |
| 114 | |
| 115 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. | |
| 116 | |
| 117 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. | |
| 118 | |
| 119 ```c | |
| 120 // Transitioning the state from HTTP to WebSocket | |
| 121 Seobeo_WebSocket_Server_Connection *p_conn = malloc(sizeof(Seobeo_WebSocket_Server_Connection)); | |
| 122 memset(p_conn, 0, sizeof(Seobeo_WebSocket_Server_Connection)); | |
| 123 | |
| 124 p_conn->p_handle = p_handle; | |
| 125 p_conn->is_active = TRUE; | |
| 126 p_conn->fragment_capacity = 4096; | |
| 127 p_conn->fragment_buffer = malloc(p_conn->fragment_capacity); | |
| 128 | |
| 129 ``` | |
| 130 | |
| 131 --- | |
| 132 | |
| 133 ## Frame-Based Protocols | |
| 134 | |
| 135 This is where the logic gets "cancerous." WebSockets don't just send raw strings; they wrap everything in a **Frame**. | |
| 136 | |
| 137 ### The Opcode Table | |
| 138 | |
| 139 The first byte contains the `FIN` bit (is this the end of the message?) and the `Opcode` (what kind of data is this?). | |
| 140 | |
| 141 | Opcode (Hex) | Meaning | Description | | |
| 142 | --- | --- | --- | | |
| 143 | `0x0` | Continuation | Part of a multi-frame message | | |
| 144 | `0x1` | Text | UTF-8 payload | | |
| 145 | `0x2` | Binary | Raw binary data | | |
| 146 | `0x8` | Close | Terminate the connection | | |
| 147 | `0x9` | Ping | Heartbeat check | | |
| 148 | `0xA` | Pong | Heartbeat response | | |
| 149 | |
| 150 ### The Masking Rule | |
| 151 | |
| 152 * **Client to Server:** MUST be masked. | |
| 153 * **Server to Client:** MUST NOT be masked. | |
| 154 If a client sends unmasked data, the server must close the connection. It’s the law. | |
| 155 | |
| 156 ### Why the Bitwise Mess? (Endianness) | |
| 157 | |
| 158 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. | |
| 159 | |
| 160 --- | |
| 161 | |
| 162 ## Sending a Frame (Client Side) | |
| 163 | |
| 164 Here is how we construct a frame to send data to the server. | |
| 165 | |
| 166 ```c | |
| 167 uint8 frame[14]; | |
| 168 size_t frame_len = 0; | |
| 169 | |
| 170 // Byte 0: FIN bit (0x80) and Opcode | |
| 171 frame[0] = (fin ? 0x80 : 0x00) | (opcode & 0x0F); | |
| 172 frame_len++; | |
| 173 | |
| 174 // Generate a 4-byte mask key | |
| 175 uint8 mask_key[4]; | |
| 176 for (int i = 0; i < 4; i++) | |
| 177 mask_key[i] = (uint8)(rand() % 256); | |
| 178 | |
| 179 // Byte 1+: Payload Length logic | |
| 180 if (payload_length < 126) { | |
| 181 frame[1] = 0x80 | (uint8)payload_length; // 0x80 sets the MASK bit | |
| 182 frame_len++; | |
| 183 } else if (payload_length <= 65535) { | |
| 184 frame[1] = 0x80 | 126; | |
| 185 frame[2] = (uint8)((payload_length >> 8) & 0xFF); | |
| 186 frame[3] = (uint8)(payload_length & 0xFF); | |
| 187 frame_len += 3; | |
| 188 } else { | |
| 189 frame[1] = 0x80 | 127; | |
| 190 for (int i = 0; i < 8; i++) | |
| 191 frame[2 + i] = (uint8)((payload_length >> (56 - i * 8)) & 0xFF); | |
| 192 frame_len += 9; | |
| 193 } | |
| 194 | |
| 195 // Attach the mask key | |
| 196 memcpy(frame + frame_len, mask_key, 4); | |
| 197 frame_len += 4; | |
| 198 | |
| 199 ``` | |
| 200 | |
| 201 To actually send the data, you XOR every byte with the mask: | |
| 202 | |
| 203 ```c | |
| 204 for (size_t i = 0; i < length; i++) | |
| 205 data[i] ^= mask_key[i % 4]; | |
| 206 | |
| 207 ``` | |
| 208 | |
| 209 --- | |
| 210 | |
| 211 ## Receiving a Frame (Server Side) | |
| 212 | |
| 213 On the server side, we have to do the reverse. We peel the onion layer by layer. | |
| 214 | |
| 215 #### 1. Parse the Header | |
| 216 | |
| 217 We check the first two bytes to see how big the payload is and if it's masked. | |
| 218 | |
| 219 ```c | |
| 220 uint8 *buf = p_conn->p_handle->read_buffer; | |
| 221 uint8 byte1 = buf[0]; | |
| 222 uint8 byte2 = buf[1]; | |
| 223 | |
| 224 boolean fin = (byte1 & 0x80) != 0; | |
| 225 Seobeo_WebSocket_Opcode opcode = (Seobeo_WebSocket_Opcode)(byte1 & 0x0F); | |
| 226 boolean masked = (byte2 & 0x80) != 0; | |
| 227 uint64 payload_len = byte2 & 0x7F; | |
| 228 | |
| 229 size_t header_len = 2; | |
| 230 | |
| 231 ``` | |
| 232 | |
| 233 #### 2. Handle Extended Lengths | |
| 234 | |
| 235 If the length is 126 or 127, it means the actual size is hidden in the next 2 or 8 bytes. | |
| 236 | |
| 237 ```c | |
| 238 if (payload_len == 126) { | |
| 239 payload_len = (buf[2] << 8) | buf[3]; | |
| 240 header_len += 2; | |
| 241 } else if (payload_len == 127) { | |
| 242 payload_len = 0; | |
| 243 for (int i = 0; i < 8; i++) | |
| 244 payload_len = (payload_len << 8) | buf[2 + i]; | |
| 245 header_len += 8; | |
| 246 } | |
| 247 | |
| 248 ``` | |
| 249 | |
| 250 #### 3. Unmask the Payload | |
| 251 | |
| 252 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. | |
| 253 | |
| 254 ```c | |
| 255 uint8 mask_key[4] = {0}; | |
| 256 if (masked) { | |
| 257 memcpy(mask_key, buf + header_len, 4); | |
| 258 header_len += 4; | |
| 259 } | |
| 260 | |
| 261 uint8 *payload = malloc(payload_len); | |
| 262 memcpy(payload, buf + header_len, payload_len); | |
| 263 | |
| 264 if (masked) | |
| 265 Seobeo_WebSocket_Unmask_Data(payload, payload_len, mask_key); | |
| 266 | |
| 267 ``` | |
| 268 | |
| 269 --- | |
| 270 | |
| 271 ## Conclusion | |
| 272 | |
| 273 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. | |
| 274 | |
| 275 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. |