Project 12: WebSocket Chat Server

A WebSocket server that upgrades HTTP connections, handles the WebSocket framing protocol, and enables real-time bidirectional chat. Works with browser WebSocket clients.

Quick Reference

Attribute Value
Primary Language C++
Alternative Languages Rust, Go, JavaScript (Node)
Difficulty Level 3: Advanced
Time Estimate 2 weeks
Knowledge Area WebSocket Protocol, HTTP Upgrade, Framing
Tooling Real-time communication backend
Prerequisites Project 6, understanding of HTTP

What You Will Build

A WebSocket server that upgrades HTTP connections, handles the WebSocket framing protocol, and enables real-time bidirectional chat. Works with browser WebSocket clients.

Why It Matters

This project builds core skills that appear repeatedly in real-world systems and tooling.

Core Challenges

  • HTTP upgrade handshake → maps to Sec-WebSocket-Key, SHA-1, Base64
  • Frame parsing → maps to opcode, length, masking
  • Ping/pong for keepalive → maps to control frames
  • Handling fragmented messages → maps to assembling frames

Key Concepts

  • WebSocket Protocol: RFC 6455
  • HTTP Upgrade: “High Performance Browser Networking” Chapter 17 - Grigorik
  • Framing Format: RFC 6455 Section 5
  • SHA-1 and Base64: Standard cryptographic libraries

Real-World Outcome

$ ./websocket_server 8080
WebSocket server listening on port 8080

# Browser connects to ws://localhost:8080
# HTML client:
<script>
const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = (e) => console.log('Received:', e.data);
ws.onopen = () => ws.send('Hello from browser!');
</script>

# Server logs:
[12:00:01] HTTP upgrade request from 127.0.0.1:54321
[12:00:01] WebSocket handshake complete
[12:00:02] Received TEXT: "Hello from browser!"
[12:00:02] Broadcasting to 3 clients
[12:00:05] Sending PING to 127.0.0.1:54321
[12:00:05] Received PONG

Implementation Guide

  1. Reproduce the simplest happy-path scenario.
  2. Build the smallest working version of the core feature.
  3. Add input validation and error handling.
  4. Add instrumentation/logging to confirm behavior.
  5. Refactor into clean modules with tests.

Milestones

  • Milestone 1: Minimal working program that runs end-to-end.
  • Milestone 2: Correct outputs for typical inputs.
  • Milestone 3: Robust handling of edge cases.
  • Milestone 4: Clean structure and documented usage.

Validation Checklist

  • Output matches the real-world outcome example
  • Handles invalid inputs safely
  • Provides clear errors and exit codes
  • Repeatable results across runs

References

  • Main guide: LEARN_CPP_NETWORK_PROGRAMMING.md
  • “High Performance Browser Networking” by Ilya Grigorik