- One request returns one response
- The connection closes after the exchange
Websocket Protocol
Socket Programming with a FastAPI real-time demo chat app
Amirhossein Khalili • Morteza Khanbabaie • Alireza Khosravi
WebSocket History Timeline
The communication model evolved from simple request/response to persistent real-time channels.
Classic HTTP1991
Polling1995+
Long Polling2006
WebSocket2011
Real-time Web2010s+
HTTP
A short-lived request/response cycle with no native live push.
- Every update needs a new HTTP cycle
- The server cannot push live data by itself
Polling
The browser repeatedly asks the server for new data.
- The client checks on a fixed timer
- The server answers even when nothing changed
- Many empty requests waste network work
- Latency depends on the timer interval
Long Polling
The server holds the request until an update is available.
- The server keeps the request open
- The client reconnects after each response
- Open requests consume server state
- Reconnect and timeout handling is required
WebSocket
An HTTP Upgrade creates one persistent Full-duplex channel.
- HTTP Upgrade switches the protocol
- Frames move both ways on one socket
- Each client keeps a live connection
- Scaling needs connection-aware design
WebSocket in the OSI Model
Application semantics at Layer 7, reliable byte delivery through TCP/IP.
HTTP Versions in WebSocket
Different HTTP versions start WebSocket connections differently.
- The browser sends a normal GET request with
Upgrade: websocket. - The server replies
101 Switching Protocolsif it accepts. - After that, the same TCP connection carries WebSocket frames both ways.
- This is the classic and easiest model to understand.
- HTTP/2 does not use the old connection-level Upgrade flow.
- It uses Extended CONNECT, so WebSocket traffic lives inside one HTTP/2 stream.
- Other HTTP/2 streams can share the same underlying connection.
- Support depends more on servers, clients, and proxies.
- HTTP/3 runs on QUIC over UDP instead of TCP.
- WebSocket uses a CONNECT-based mapping similar in idea to HTTP/2.
- QUIC streams reduce transport-level head-of-line blocking.
- It is modern, but the demo is easier to explain with HTTP/1.1.
Project Architecture
Browsers connect to one WebSocket endpoint; ConnectionManager groups sockets by room.
Keynotes and Takeaways
The essential points to remember from the project.
- Simple
- Stateless
- Not ideal for live push
- Easy
- Wasteful
- Interval-based latency
- Persistent
- Full-duplex
- Low latency
- Connection state
- Disconnect handling
- Scaling strategy