This post is part of some ideas I have been working on. Initially, I was just curious about how to create a web server in Java…a simple server that accepts an http request and returns a response. As expected, the Java API is extremely high level…hiding all the nitty gritty details of network programming (TCP, IP, UDP etc…). Fortunately, I found this book: Unix Network Programming which is a definite reference on sockets/networking. While it’s written in C, I found the examples quite easy to read and understand.

As usual, the code is on my repository: simple-java-web-server

Main thread:

Initializing the server:

Implementing the run method:
As long as the server is running, continuously check to see if a client wants to do something: i.e: accept, connect, read or write.

Accepting client connections and registering the client for reading:

Reading from and writing to the client:
This is a rather simple server and reading and writing is done on the same thread. Here we read all the data from the client and based on the request, write back to the client with a response.

Configuring our application with spring annotations:

Finally the Main class responsible for running the server: