As an open-source lightweight WEB server, Tomcat is not very suitable for some large projects, but it is open-source. Reading its source code can greatly improve our programming skills and design thinking. Many good design patterns are used in Tomcat, and the code style is worth following. I read the Tomcat source code analysis book a few times ago. I would like to share my learning process records. That's not good. Don't spray me.
No nonsense. Go straight to the Code on the topic. What is Tomcat? Tomcat is a web server that can receive and respond to requests. Receiving Requests and responding make us think of Socket programming. We can start a thread service ServerSocket to listen to port 8080 (configurable) on the local machine, and then access http: // localhost: 8080/index.html in the browser, at this time, you can use the inputstream of the socket to obtain the HTTP request encapsulated by the browser, and then you can make a big fuss about this request. The following is the server code.
PORT = 8080 String SHUTDOWN = "SHUTDOWN" String WEB_ROOT = System.getProperty("user.dir") + File.separator + "WebRoot" ServerSocket server = server = ServerSocket(PORT,1 InetAddress.getByName("127.0.0.1" } shutdown = (! Socket client = InputStream in = OutputStream out = client = in = out = Request request = Response response = shutdown = } }
Now that both the HTTP server and the Request are available, as the name suggests, the request must be a JAVA class that encapsulates the Request and must be able to parse the HTTP request, such as accessing static resources, you must obtain the Resource Identifier uri of the static resource.
HTTP Request class:
GET /index.html HTTP/1.1 Accept: text/html, application/xhtml+xml, *
.in = [] bytes = [2048 i = StringBuffer buffer = StringBuffer(2048 ( j=0; j<i; j++ buffer.append(( uri = } index1 = requestString.indexOf(" " (index1 != -1 index2 = requestString.indexOf(" ", index1+1 (index2> requestString.substring(index1+1 }
After obtaining the resource locator, the next step is to make the corresponding response based on the resource locator. Of course, the actual Tomcat processing method is very complicated. We only imitate the simple method to access static resources.
Response class:
BUFFER_SIZE = 2048 .out = [] bytes = InputStream in = File file = in = ((ch=in.read(bytes, 0, BUFFER_SIZE))!=-1 out.write(bytes, 0 String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 23\r\n" + "\r\n" + "
In this way, a simple Web server can access static resources and directly access the resources in the browser. If the corresponding resources are not found, the Error 404 can be returned. I will write it here today and continue to work hard...