Postly.
HomeBlogAsk
Postly.Stories worth reading.
BlogAskWriteRSS
All posts
#java#networking#http#from-scratch

Implementing HTTP/1.1 in Java using raw TCP sockets

A from-scratch HTTP/1.1 server on ServerSocket: a streaming parser, RFC header rules, keep-alive and virtual threads.

AGAryan GargDec 3, 20264 min read3 views
9
Dark cover showing a raw HTTP request and response in monospace next to the title HTTP/1.1 over raw TCP
9

TL;DR · AI summary

Learn how to implement a basic HTTP/1.1 server in Java using raw TCP sockets and virtual threads. This guide covers building a state-machine parser, handling streaming data, and managing persistent connections without relying on existing web frameworks.

Every web framework I have used hides the same thing: a socket, some bytes, and a parser that turns those bytes into a request. I wanted to see that part with nothing in between, so I implemented HTTP/1.1 in Java on top of a plain ServerSocket. No servlet container, no Netty, no com.sun.net.httpserver. Just TCP.

This post walks through how it works and what surprised me along the way.

The shape of the server

The server is three small pieces:

  • HttpServer accepts TCP connections.

  • HttpConnection owns one socket and loops over requests on it.

  • RequestReader turns a stream of bytes into a Request.

A handler is just a function from request to response:

@FunctionalInterface
public interface HttpHandler {
  Response handle(Request request);
}

Accepting connections is the easy part. Each connection gets its own virtual thread, which means I can write simple blocking code and still handle thousands of idle keep-alive connections without a thread pool tuning exercise:

private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();

public void listen() throws IOException {
  serverSocket = new ServerSocket(port);
  running = true;
  while (running) {
    Socket socket = serverSocket.accept();
    executor.execute(new HttpConnection(socket, handler));
  }
}

Before Java 21 this would have been the point where I reached for NIO selectors. With virtual threads, a blocking read() parks the virtual thread instead of an OS thread, so thread-per-connection is back on the table.

TCP is a stream, not a list of messages

The first real lesson: TCP doesn't deliver "a request". It delivers bytes, in whatever chunks the network feels like. A single read() might return half a request line, or the end of one request and the start of the next.

So the parser can't assume anything about chunk boundaries. I modeled it as a state machine:

public enum ParserState {
  INIT,     // waiting for the request line
  HEADERS,  // reading field lines until an empty line
  BODY,     // reading Content-Length bytes
  DONE
}

The reader keeps a buffer, appends whatever the socket returns, and asks the parser to consume as much as it can. The parser returns how many bytes it used. Anything left over is shifted to the front of the buffer and kept for the next read:

while (state != ParserState.DONE) {
  int bytesRead = inputStream.read(buffer, bufLen, BUFFER_SIZE - bufLen);
  bufLen += bytesRead;

  int consumed = parse(Arrays.copyOfRange(buffer, 0, bufLen));
  if (consumed > 0)
    System.arraycopy(buffer, consumed, buffer, 0, bufLen - consumed);
  bufLen -= consumed;
}

If a state needs more data than it has (a request line without its \r\n yet, for example), it consumes zero bytes and the loop reads again.

Testing with a hostile stream

How do you test that a parser survives arbitrary chunking? I wrote a tiny InputStream that hands out a fixed number of bytes per read:

public class ChunkReader extends InputStream {
  @Override public int read(byte[] b, int off, int len) {
    if (pos >= data.length) return -1;
    int n = Math.min(chunkSize, Math.min(len, data.length - pos));
    System.arraycopy(data, pos, b, off, n);
    pos += n;
    return n;
  }
}

Feeding requests through it three bytes at a time shook out every "I assumed the whole line was there" bug I had. It is the most useful twenty lines in the project, and I'd recommend the trick for any streaming parser.

Parsing the request line and headers

The request line is METHOD SP target SP HTTP/1.1 CRLF. I split on spaces, require exactly three parts, check that the method is uppercase letters and reject anything other than HTTP/1.1.

Headers have more rules than I expected. From RFC 9110:

  • Field names are case-insensitive, so I store them lowercased.

  • A field name is a token: letters, digits and a specific set of symbols like !#$%&'*+-.^_|~. Anything else (including ©) is a malformed request.

  • No whitespace is allowed between the field name and the colon. Host : x is invalid.

  • A repeated header is combined into one comma-separated value.

public void set(String name, String value) throws Exception {
  if (!isTokenValid(name)) throw new Exception("Malformed header name");
  headers.compute(name.toLowerCase(), (k, v) ->
    v == null ? value : v + "," + value);
}

An empty line ends the headers. If there's a Content-Length, the parser moves to BODY and reads exactly that many bytes. A body longer than declared, or a body with no Content-Length at all, is an error.

Responses and keep-alive

Building responses uses a small fluent API, and Content-Length is always computed from the body so I can't get it wrong:

return new Response(Status.OK)
  .header("Content-Type", "text/plain")
  .text("pong");

HTTP/1.1 connections are persistent by default, so HttpConnection loops: read a request, write a response, repeat. If the client sends Connection: close, the server echoes it and closes the socket after the response.

while (true) {
  Request request = requestReader.readRequest();
  if (request == null) break;
  boolean keepAlive = request.keepAlive();

  Response response = handler.handle(request);
  if (!keepAlive) response.header("Connection", "close");
  response.writeTo(out);

  if (!keepAlive) break;
}

A logger that doesn't block requests

Printing to the console from many threads is slow and interleaves output. I built a small logger whose async sink pushes lines onto a BlockingQueue and lets a single daemon thread write them. Shutdown sends a "poison pill" message so the worker drains the queue and exits cleanly:

private void runLoop(PrintStream stream) throws InterruptedException {
  while (true) {
    String line = queue.take();
    if (line.equals(POISON_PILL)) break;
    stream.print(line);
    stream.flush();
  }
}

What I learned (and what's next)

  • Bytes versus characters matters. Content-Length counts bytes, but my body builder counts Java chars. That works for ASCII and breaks for a UTF-8 body with an emoji in it. The fix is to accumulate the body in a ByteArrayOutputStream and decode only at the end.

  • Limits are a feature. A real server caps the size of the request line and headers and sets a read timeout with socket.setSoTimeout(). Without them, one slow client can hold a connection open forever.

  • Chunked transfer encoding is the next thing to add, since it's how HTTP/1.1 streams bodies of unknown length.

  • Virtual threads made the concurrency model boring, in the best way.

The most valuable part of this project wasn't the server. It was finally understanding what every framework I use does before my code ever runs.

On this page

  • The shape of the server
  • TCP is a stream, not a list of messages
  • Testing with a hostile stream
  • Parsing the request line and headers
  • Responses and keep-alive
  • A logger that doesn't block requests
  • What I learned (and what's next)

Discussion(0)

    Loading comments…