Almost everything available on the Internet is served by web server. There are plenty of web server implementations like Apache, Nginx, Express, etc. But ever wondered how to implement a web server from scratch without any external dependencies? I wondered about that and this post is the result of that little experiment using Java.
Before listing the goals, this post assumes that you have some knowledge of HTTP. Mozilla has a very good overview here. Now the goals
- Java version 8+
- No external dependencies
- Extremely rudimentary simple Web server
- Servers only one static file (index.html) for path / or returns 404
- Supports only GET for other methods returns 501
Upon launching the server starts listening to port 8080. Whenever a new request hits the server, a new thread is spawned and further processing of the request is the responsibility of this thread. In the run method of the thread, we do some basic checking to see if we can handle this request or not. If the request is method is other than GET, we return 501 or if the request is other than “/” we return 404 otherwise we return 200. In each of these three cases we return a static file.
Static file: index.html
Static file: 404.html
Static file: 501.html
Parsing the header
Along with each HTTP request the client, in most cases a Browser, will send in some headers. The first header gives the details about the HTTP method, the requested resource and finally the protocol version. A typical request will look like
GET /index.html HTTP/1.1
Clients will also send other headers most often Accept: which tells what MIME types the client can handle. CLI clients like curl will just send */*, which means accepts everything. For purposes of this project we only care about the first header and ignore the rest of the headers.
Show me the code
Similar to the request, the server response also has headers before the content. Of all the headers that the server can set, the Status, Date, Content-Type, and Content-Length are required. The Date has to be always in GMT.
This implementation takes a lot of things for granted, but it is a good place to start. In future posts lets refactor this into more modular server. All of the code can be found on Github at https://github.com/cx0der/http-server.