← Build Your Own HTTP Server
Stage 4: Keep-Alive & Pipelining
stage 4 of 4 · ~30 min · runs in your browser
Real connections don't carry one request. With keep-alive, a client sends
several requests down one socket — sometimes back-to-back before you've
answered the first (pipelining). Your server must split the byte stream
into requests using Content-Length, answer each in order, and know when
to hang up.
Implement handleConnection(buffer, handler):
buffermay contain multiple requests back-to-back; each request's body length comes from itsContent-Lengthheader (0 if absent)- call
handler(rawRequest)for each complete request, in order, and collect the returned response strings - connection rules (HTTP/1.1): keep going by default; stop after a
request with
Connection: close(case-insensitive) — later bytes are ignored - return
{ responses, close }wherecloseis true if you stopped early
tests (5)
○ a single request round-trips
○ pipelined requests answered in order
○ bodies are sliced by Content-Length
○ Connection close stops the loop
○ header lookup is case-insensitive
handleConnection.js