Simple multithreaded Java Webserver

The following code (estimated 150 lines of code) implements a simple multithreaded Web Server in Java. The code is easy to read and contains no (really) complicated stuff. There are 5 classes:

HTTPException.java

This class extends Exception and overrides the getMessage(String) Methode, which is responsibe for example for the Error 404 Not Found message.

MimeTypeResolver.java

This class is a static Map of file type to mimetype mappings. It can be extended easily.

RequestWorker.java

This class extends the Thread class and can and is run as a thread therefore. For every request occurring in the Server class, a new RequestWorker is created which handles the user request. Note that this class is kept ultra simple. It converts the path part of the HTTP request to a file path and servers this file back to the user.

Server.java

This class also inherits from the Thread class and is run as such. It creates a ServerSocket and creates a RequestWorker thread for each request.

Status.java

This is an Enum containing the HTTP codes and its corresponding error messages.

When started, the server serves the content in the root folder. Open your browser and type http://localhost:8080. When everything is okay, you see the welcome website.

Download the source code here: SimpleJavaWebServer.

Leave a comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.