Tomcat source Analysis (ii)------the inside and outside of a complete request.

Source: Internet
Author: User
Tags http request sleep socket thread throwable tomcat

A few days ago, we analyzed the architecture and startup process of Tomcat and began to study its workings today. Tomcat is essentially a Web server that can run Jsp/servlet, so the most typical application is that the user accesses the server through a browser, and the Tomcat receives the request and forwards it to the servlet, which, after processing by the servlet, returns the result to the client. The internal mechanism of such a complete request is specifically resolved today.

Through debug, along the way, we find that the core process of Tomcat processing requests is the following: The endpoint,endpoint that initiates a pre-support protocol starts with a dedicated thread that listens to the request for the Protocol, and by default, it starts Jioendpoint, Jioendpoint based on the Java ServerSocket receive HTTP request ServerSocket received the client request of the socket, packaging, and all the way from host to wrapper, and then request to the appropriate servlet

The following will focus on the above two processes.

Through the previous analysis (Tomcat source analysis one) can know that when Tomcat boots will start connector, connector will be protocolhandler to start the endpoint. By default, Tomcat launches two connector, the HTTP protocol and the AJP protocol, corresponding to Http11protocol and Ajpprotocol in turn, both of which start jioendpoint. Here's a look at the start method of Jioendpoint:

[Java] View Plain copy print? Public void start ()  throws Exception {       //  Initialize socket if not done before        if  (! Initialized)  {           init ();        }       if  (!running)  {            running = true;            paused = false;           // Create  Worker collection            if  (Getexecutor ()   == null)  {                Createexecutor ();           }   &NBSP;&NBSp;      // start acceptor threads             for  (int i = 0; i < acceptorthreadcount;  i++)  {               thread  acceptorthread = new thread (New acceptor (),  getname ()  +  "-Acceptor-"  + i);                Acceptorthread.setpriority (threadpriority);                acceptorthread.setdaemon (Getdaemon ());                acceptorthread.start ();            }       }  }   public void Start () throws Exception {// Initialize Socket IF Not-Done before if (!initialized) {init ();} if (!running) {running = true; paused = false;//Create worker Collection if (getexecutor () = = null) {Createexecutor ();}//Start acceptor threads for (int i = 0; i < Acceptorthreadcount; i+ +) {Thread acceptorthread = new Thread (New acceptor (), getName () + "-acceptor-" + i); Acceptorthread.setpriority (THREADPR iority); Acceptorthread.setdaemon (Getdaemon ()); Acceptorthread.start (); }}} 

The above code is very clear to start acceptorthreadcount threads, each thread by the acceptor agent, specifically see the acceptor Run method:

[Java] View Plain copy print? Public void run ()  {       // Loop until we  Receive a shutdown command        while  (running)  {            // loop if endpoint is paused            while  (paused)  {                try {                    thread.sleep (;  )              } catch  (interruptedexception  e)  {                    // ignore                }           }            // Accept the next incoming connection from  The server socket            try {               Socket socket =  Serversocketfactory.acceptsocket (serversocket);                serversocketfactory.initsocket (socket);                // Hand this socket off to an  Appropriate processor                 if  (!processsocket (socket))  {                    // close socket right away                     try {                        socket.close () ;                   }  catch  (ioexception e)  {                        // ignore                     }                }            }catch  ( IOException x )  {                if  ( running )  log.error (sm.getstring ("Endpoint.accept.fail"),  x );           } catch  (throwable t)  {                log.error (Sm.getString (" Endpoint.accept.fail "),  t);           }           // the processor will recycle itself  when it finishes        }  }   public void run () { Loop until we receive a shutdown command while (running) {//loop if endpoint are paused while (paused) {try {Thread. Sleep (1000); } catch (Interruptedexception e) {//Ignore}}//Accept the next incoming connection from the server socket try {Socke T socket = Serversocketfactory.acceptsocket (ServerSocket); Serversocketfactory.initsOcket (socket); Hand this socket off to an appropriate processor if (!processsocket (socket)) {//Close socket right away try {socket. Close (); } catch (IOException e) {//Ignore}}}catch (IOException x) {if (running) log.error (sm.getstring ("endpoint.accept"). Fail "), x); } catch (Throwable t) {Log.error (sm.getstring ("Endpoint.accept.fail"), t);}//The processor would recycle itself when it Finishes}} 

This leads to the conclusion that Tomcat receives a client request by ServerSocket listening to the socket. The specific code does not need me to parse, a little understanding of Java net people can understand the above code, Tomcat is the most standard and the most basic socket invocation method to handle the network request. After finding the source of the processing request, the following is the thing to do is simple, hit the breakpoint, in the browser to request a simple Hello world, debug all the way down. Along the way, the sequence diagram for the main process is as follows:

From the above figure, the above process can be decomposed into the following three main core points: based on the Http1.1 protocol to the socket parsing and packaging standardenginevalve, Standardhostvalve, Standardcontextvalve and standardwrappervalve four types of valve inoke. Four different levels of valve have done different levels of processing and encapsulation based on the responsibility chain model Applicationfilterchain implementation of filter interception and actual servlet requests

The above three core points are very rich research points, which will be analyzed one by one in the following days.

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.