Quest tomcat--Start with a humble web server

Source: Internet
Author: User

Objective:

Whether it is the previous internship unit small to a 35 person to do the project, or now a more than hundred people in the product, has been able to see Tomcat figure. The work often encountered in the operation is to start and close the Tomcat service, or modify the touch of a Java file, compile the file, the generated class file into the Tomcat directory in the corresponding jar package to make it effective, but also can be hot deployment, do not need such cumbersome operation.

In short, has been accustomed to the existence of Tomcat, did not delve into Tomcat's operating mechanism and principles, the last time for the Tomcat source of the eager or last year's matter-"quest Tomcat (a)--myeclipse import tomcat source." In this article, I downloaded the tomcat6 version of the code, and import it into eclipse, after more than a year, the original project is still in, but in good faith, I still do a lot of import Tomcat source to eclipse operation.

The reverence for Tomcat made me decide to delve into it. So I found online everyone's most popular textbook-"deep analysis of Tomcat", the book is older, but very authoritative, does not affect the understanding of the principle of things. The second chapter has now been seen.

Read or understand the book should know, this is not a book directly to tell you the design of Tomcat, the use of what design patterns or the source of a line of what is the originality of the place. The book takes a gradual approach from a simple, easy-to-use servlet container, and then slowly enriches and adds a functional module that eventually forms what we want to know about Tomcat.

Background knowledge:

    • HTTP request:

Request Method--Uniform Resource Identifier uri--Protocol/version

Request Header

Entity

For example, here we can see the method requested is GET, request URL is http://tech.qq.com/a/20160604/007535.htm, and there are Request and the following response requests header information, such as Content-type and so on.

    • HTTP Total Support 7 in Request method

    GET,POST,HEAD,OPTIONS,PUT,DELETE,TRACE

    • HTTP response

Protocol--Status code--description

Response header

Response Entity Segment

    • Socket

The socket is used in the application to read data from the network, implementing communication between different computers, and implementing a socket that needs to know the IP address and port number of the corresponding application.

You first create an instance of the socket class, and with that instance, you can use it to send or receive a byte stream. If you want to send a byte stream, you need to call the Getoutputstream of the socket class to get a Java.io.OutputStream object; To send text to a remote application, you need to use the returned The OutputStream object creates a Java.io.PrintWriter object, and to receive a byte stream from the other end of the connection, the getInputStream method of the socket class needs to be called , which returns a The Java.io.InputStream object.

    • ServerSocket class

With the client socket can send the request, if there is no service side to respond, send the request is also meat bun hit the dog, ServerSocket is to serve as the role of the server,serversocket out of standby state, once a client makes a request , theServerSocket will be given a response to communicate with the client.

Request Response Model

With this background knowledge, we can implement a simple to burst communication model, create a new socket client communication class for sending and receiving data, and create a server-side ServerSocket for listening and responding to client requests.

It consists of the following three classes:

  Httpserver: Simulating a Web server

Package Mytest;import Java.net.socket;import Java.net.serversocket;import java.net.inetaddress;import Java.io.inputstream;import Java.io.outputstream;import Java.io.ioexception;import Java.io.File;public class   Httpserver {/** web_root is the directory where we have HTML and other files reside.   Web_root is the "Webroot" directory under the working * directory.   * The working directory is the location of the file system * from where the Java command was invoked.  */public static final String web_root = System.getproperty ("User.dir") + File.separator + "Webroot";  Shutdown command private static final String Shutdown_command = "/shutdown";  The shutdown command received private Boolean shutdown = false;    public static void Main (string[] args) {httpserver server = new Httpserver ();  Server.await ();    } public void await () {ServerSocket serversocket = null;    int port = 8080; try {serversocket = new ServerSocket (port, 1, InetaDdress.getbyname ("127.0.0.1"));      } catch (IOException e) {e.printstacktrace ();    System.exit (1);      }//Loop waiting for a request while (!shutdown) {socket socket = NULL;      InputStream input = null;      OutputStream output = null;        try {socket = serversocket.accept ();        input = Socket.getinputstream ();        Output = Socket.getoutputstream ();        Create request object and parse Request request = new request (input);        Request.parse ();        Create Response object Response Response = new Response (output);        Response.setrequest (Request);        Response.sendstaticresource ();        Close the socket Socket.close ();      Check if the previous URI is a shutdown command shutdown = Request.geturi (). Equals (Shutdown_command);        } catch (Exception e) {e.printstacktrace ();      Continue }    }  }}

  

As you can see from the code:

    1. The sockets and ServerSocket are created in the class respectively;
    2. Defines a Web_root directory in which the corresponding result file for the corresponding request is stored;
    3. Defines a close command to close the Web server by entering a similar .../shutdown in the browser
    4. An await method has been created that listens to the 127.0.0.1 8080 port, and if a request is made (such as entering a request address in a browser), it enters the await method and executes ServerSocket's accept method.

Request class:

Simulates an HTTP request.

Package Mytest;import Java.io.inputstream;import Java.io.ioexception;public class Request {private InputStream input;  Private String URI;  Public Request (InputStream input) {this.input = input;    } public void Parse () {//Read a set of characters from the socket stringbuffer request = new StringBuffer (2048);    int i;    byte[] buffer = new byte[2048];    try {i = input.read (buffer);      } catch (IOException e) {e.printstacktrace ();    i =-1;    } for (int j=0; j<i; J + +) {request.append ((char) buffer[j]);    } System.out.print (Request.tostring ());  URI = Parseuri (request.tostring ());    } private String Parseuri (string requeststring) {int index1, index2;    Index1 = Requeststring.indexof (");      if (index1! =-1) {index2 = Requeststring.indexof (", index1 + 1);    if (Index2 > Index1) return requeststring.substring (index1 + 1, index2);  } return null;  } public String GetURI () {return URI; }}

  

From the code you can find:

    1. Can be implemented to pass InputStream object, in processing the client communication with the socket object to obtain;
    2. Call the read of the InputStream object to get the raw data for the HTTP request;
    3. The parse method is used to parse the original data in the HTTP request (the original data is obtained from the above getinputstream);
    4. Parseuri is called by Parse as a private method to parse the URI of the HTTP request

Response class:

Simulates the HTTP response.

Package Mytest;import Java.io.outputstream;import Java.io.ioexception;import java.io.fileinputstream;import java.io.file;/* HTTP Response = Status-line * ((general-header | response-header | entity-header) CRLF) CRLF [  Message-body] Status-line = http-version sp Status-code sp reason-phrase Crlf*/public class Response {private static  Final int buffer_size = 1024;  Request request;  OutputStream output;  Public Response (OutputStream output) {this.output = output;  } public void Setrequest (Request request) {this.request = Request;    } public void Sendstaticresource () throws IOException {byte[] bytes = new Byte[buffer_size];    FileInputStream FIS = null;      try {File File = new file (Httpserver.web_root, Request.geturi ());        if (file.exists ()) {FIS = new FileInputStream (file);        int ch = fis.read (bytes, 0, buffer_size);          while (ch!=-1) {output.write (bytes, 0, ch);        ch = fis.read (bytes, 0, buffer_size);   }   } else {//File not found String errormessage = ' http/1.1 404 File Not found\r\n ' + ' Conte nt-type:text/html\r\n "+" content-length:23\r\n "+" \ r \ n "+" 

  

From the code can be found:

    1. similar to request, the response object was constructed by accepting OutputStream;
    2. The Setrequest method is used to receive the request object because the GetURI method of the request is required in the response;
    3. The Sendstaticresource method is primarily used to handle request responses, such as sending a static resource HTML as the result of a request

So far, this article mainly mentions:

    • Some basic concepts such as HTTP request, HTTP response, socket, etc.;
    • Have a basic understanding of a super-humble web server;
    • Identify the roles and responsibilities of the client and the service side.

If you feel that reading this article is helpful to you, please click " recommend " button, your "recommendation" will be my biggest writing motivation! If you want to keep an eye on my article, please scan the QR code, follow Jackiezheng's public number, I will push my article to you and share with you the high-quality articles I have read every day.

  

Quest tomcat--Start with a humble web server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.