1 Introduction
This paper describes a simple implementation of HTTP server, using Java Programing Language. Multi-thread (Package: java.util.concurrency ) and buffer (Package: java.io and java.net) is used in this implementation. Although it’s very simple, It’s helps to understand that how an HTTP server actually works.
2 Implementation details
2.1 Software Architecture
Picture1. UML Class Diagram of the HTTP Server
This simple HTTP server consises of four classes: Request class andRespons class that imitate HTTP request datagram and HTTP Response datagram, Server class which analogies the process that create threads(defined by RequestProcessor class) to receive HTTP request and create HTTP response.
When the HTTP sever start up, Server object’s run() method create threads (the number of these threads is defined by numThreads field). These threads are suspended waiting for the static field: pool, whose type is LinkedList and stores Http Request arraived.
When a HTTP request arrives, Server object’s run() method will store Http Request in the pool field and call notifyAll() method to wake up a thread that is waiting for this field(by calling RequestProcessor.processRequest() method). Any thread that is waken up will handle HTTP request and produce HTTP response then write the response back to socket.
2.2 Some tips
(1) java.net.Socket.getInputStream().read() method will blocks when there is no data coming via socket. In this implementation, Socket.SetSoTimeOut(100) is used to make read() method blocks for 100 ms when there is no data arrives. If not do so, A thread can not both handle socket input and write data back to the socket. There is also other alternatives that will be talked later.
(2)An HTTP Response’s header ends with “\r\n\r\n”.
(3)Socket.isCannected() returns true if this socket has ever been connected successfully even it’s closed now. Socket.isClosed() return true if this socket has been closed or it never been connected successfully.
(4) A socket will be close when calling Socket.getInputStream().close() or Socket.getOutputStream().close().
2.3 Source Code
See at https://github.com/Jitianyu/simple-http-sever.
3 Improved schema
The implementation talked above is rather austere, here is a few features that could be add according book [1]:
(1) spawning too many threads and switch them will cause nontrivial overhead. So considering use java package: java.nio implement the non-block reading() and writing();
(2) Implements a server administration interface;
(3) Support for CGI programs and/or the Java Servlet API;
(4) A log system in common web log file format;
(5) Server-side includes and/or Java Server Pages and so on.
Reference
[1] Harold E R. Java Network Programming, 3rd Edition[J]. Oreilly Media, 2004.