How Tomcat works learning-How far can we go series (8)

Source: Internet
Author: User
How far can we go series (8)

Nonsense:

How far can we go? I want to remind myself not to stop learning and blog updates. This series will always be related to web development. My goal is to write 100. Let's take a look at the progress of 15 goals. Haha

If you study well, do it well. If you do well, do it well!

Subject:

In the last round of study: servlet-How far can we go? series (7) discover that to understand servlet in the Web, you still need to learn servlet container: Tomcat (because it is open source !)

In order not to get lost in the vast source code of Tomcat, I first learned some peripheral knowledge, and then read the first chapter of how Tomcat works. Someone commented that this book isCodeToo many. I like this writing style very much,ProgramThe code is ours.Article!

HTTP (Hypertext Transfer Protocol ):

To view HTTP messages, you can use a packet capture tool such as Wireshark to capture HTTP messages. (Wireshark is a good packet capture tool, with a pretty nice interface and powerful functions .)
Download: http://www.wireshark.org/download.html

Packets captured when accessing the Website: including request and Response (excluding body)

Detailed learning of HTTP protocol can be viewed: http://www.cnblogs.com/tankxiao/archive/2012/02/13/2342672.html

Where get or post about method can be viewed: http://www.cnblogs.com/killbug/archive/2012/08/05/2624286.html

A simple Webserver:

Now that you know the HTTP message format, you can learn the Code provided in Chapter 1 of how Tomcat works.

Divided into three parts:

Httpserver: listens to the server port, sends the listening message to the request for processing, and removes the response of the instance.

Request: retrieves the URI from the HTTP message.

Response: According to the URI obtained by the request, read the content in the response file and return the content.

The above process basically completed the response-returned results.

Httpserver:

 Package  Code. tomcat. simplewebserver;  Import  Java. Io. file;  Import Java. Io. ioexception;  Import  Java. Io. inputstream;  Import  Java. Io. outputstream;  Import  Java.net. inetaddress;  Import  Java.net. serversocket;  Import  Java.net. Socket;  Public   Class  Httpserver {  // Project folder      Public   Static   Final String web_root = system. getproperty ("user. ID") + file. Separator + "webroot" ;  //  Shutdown command      Private   Static   Final String shutdown_command = "/shutdown" ;  //  Determine whether the shutdown identifier is used to control the program running      Private  Boolean Isshutdown = False  ;  //  Main Program      Public   Static   Void  Main (string [] ARGs) {httpserver httver = New  Httpserver ();  //  It cannot be wait, you know  Httver. Await ();}  Private  Void  Await () {serversocket = Null  ;  Int Port = 8080 ;  Try  {  //  Wait for port messages with serversocket Serversocket = New Serversocket (port, 1, inetaddress. getbyname ("127.0.0.1" ));}  Catch (Ioexception e) {e. printstacktrace (); system. Exit ( 1 ); //  When an exception occurs, disable all Java virtual machines.  }  While (! Isshutdown) {Socket socket = Null  ; Inputstream Input = Null  ; Outputstream output = Null  ;  Try {  //  Establish socket Socket = Serversocket. Accept ();  //  Socket Input Input = Socket. getinputstream ();  //  Socket output Output = Socket. getoutputstream (); Request request = New  Request (input); Request. parse (); //  Request to parse the URI Response response = New  Response (output); response. setrequest (request );  //  Put the request in the URI to be parsed. Response. sendstaticresource (); //  Send the returned content  //  Disable socket  Socket. Close (); isshutdown = Request. geturi (). Equals (shutdown_command );} Catch  (Ioexception e) {e. printstacktrace ();  Continue  ;}}}} 

Request:

 Package  Code. tomcat. simplewebserver;  Import  Java. Io. ioexception;  Import  Java. Io. inputstream;  Public   Class  Request {  Private Inputstream input;  Private  String URI;  Public  Request (inputstream input ){  This . Input = Input ;}  Public   Void  Parse () {stringbuffer request = New Stringbuffer (2048 );  Int  I; Byte [] Buffer = New   Byte [2048 ];  Try  {  //  Read the inputstream and put it into the byte [2048] buffer. I = Input. Read (buffer );}  Catch  (Ioexception e) {e. printstacktrace (); I =-1 ;}  // Passed To stringbuffer          For ( Int J = 0; j <I; j ++ ) {Request. append ((  Char  ) Buffer [J]);}  //  Then pass the parsing method in the form of string Uri = Parseuri (request. tostring ());}  //  The method used to parse the URI is equivalent to the first line of the request: Get/killbug/HTTP/1.1 to retrieve the "/killbug/" section, that is, the section between two spaces.      Private String parseuri (string requeststring ){  Int  Index1, index2;  //  The first space position Index1 = requeststring. indexof ('' );  If (Index1! =-1 ){  //  Second Space Position Index2 = requeststring. indexof ('', index1 + 1 );  If (Index2>Index1)  //  Truncate the required section based on the positions of two spaces.                  Return Requeststring. substring (index1 + 1 , Index2 );}  Return   Null  ;}  Public  String geturi (){  Return  Uri ;}} 

Response:

 Package  Code. tomcat. simplewebserver; Import  Java. Io. file;  Import  Java. Io. fileinputstream;  Import  Java. Io. ioexception;  Import  Java. Io. outputstream;  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 ){  This . Request = Request ;}  Public   Void Sendstaticresource () Throws Ioexception {  Byte [] Bytes = New   Byte  [Buffer_size];  //  File input stream Fileinputstream FCM = Null  ;  //  Request. geturi () is equivalent to: "/killbug/". Locate the path and file to a specific file. It can be an HTML file in the project. File file = New  File (httpserver. web_root, request. geturi ()); If  (File. exists () {fiis = New  Fileinputstream (File );  Int Ch = FCM. Read (bytes, 0 , Buffer_size );  While (Ch! =-1 ){  //  Write it into the output of the socket, and the return value is returned. Output. Write (bytes, 0 , CH); ch = FCM. Read (bytes, 0 , Buffer_size );}} Else { //  The file cannot be found, which is equivalent to 404. String errormessage = "HTTP/1.1 404 file not found \ r \ n" + "Content-Type: text/html \ r \ n" + "Content-Length: 23 \ r \ n "+" \ r \ n "+"  ; Output. Write (errormessage. getbytes ());}}} 
  Knowledge about Tomcat:

1. Tomcat directory structure:

Windows (the directory structure in Linux is similar ):

 

Respective roles of folders:

Bin: stores script files for starting and disabling Tomcat on various platforms. one file is Catalina. bat, open the WINDOS configuration file, and add the JDK path to the non-annotation line. For example, after saving set java_home = c: \ j2sdk1.4.2 _ 06, the Tomcat environment is configured. startup. bat is the file for starting tomcat in windows, shutdown. bat is used to close Tomcat files.

Work: Tomcat stores various servlet files generated by JSP in this directory.

Logs: stores Tomcat log files.

Conf: tomcat configuration files, the most important of which is server. xml

Lib: stores two app-admin and manager applications that come with tomcat in the server/webapps directory, and uses them to manage tomcat-Web Services. in the server/lib directory, store all required by the Tomcat server. Web applications cannot access jar files.

Temp: stores temporary files during Tomcat running ;,

2. Tomcat connections:

In the <connector.../> configuration in the tomcat configuration file server. XML, the parameters related to the number of connections include:
Minprocessors: Minimum number of idle connection threads to improve system processing performance. The default value is 10.
Maxprocessors: Maximum number of connection threads, that is, the maximum number of concurrent requests. The default value is 75.
Acceptcount: Maximum number of connections allowed. It must be greater than or equal to maxprocessors. The default value is 100.
Enablelookups: whether to check the domain name. The value is true or false. Set to false to improve processing capability.
Connectiontimeout: the network connection times out. Unit: milliseconds. If it is set to 0, it indicates that the request Never times out. This setting has potential risks. Generally, it can be set to 30000 ms.
The parameters related to the maximum number of connections are maxprocessors and acceptcount.To increase the number of concurrent connections, increase these two parameters at the same time.
The maximum number of connections allowed by the Web server is also subject to the kernel parameter settings of the operating system. Generally, Windows has about 2000 connections, and Linux has about 1000 connections. For more information about how to set these parameters in UNIX, see Common Unix monitoring and management commands.
Tomcat4 configuration example:
<Connector classname = "org. Apache. Coyote. tomcat4.coyoteconnector"
Port = "8080" minprocessors = "10" maxprocessors = "1024"
Enablelookups = "false" redirectport = "8443"
Acceptcount = "1024" DEBUG = "0" connectiontimeout = "30000"/>

Configure listening for other ports, and so on.

3. How to Increase the memory available for Tomcat

By default, Tomcat can use 128 MB of memory. In large application projects, this memory is insufficient and needs to be increased.
In UNIX, add the following settings before the file {tomcat_home}/bin/Catalina. sh:
Java_opts = '-XMS [initial memory size]-xmx [maximum memory available ]'
You need to increase the value of these two parameters. For example:
Java_opts = '-xms256m-xmx512m'
Indicates that the initial memory is 256 MB, and the maximum memory available is 512 MB.

4. About Virtual Hosts

In the Tomcat server, configure the name attribute of <Engine name = "Catalina" defaulthost = "localhost">

<Realm classname = "org. Apache. Catalina. realm. userdatabaserealm"
Resourcename = "userdatabase"/>

<Host name = "localhost" appbase = "webapps"
Unpackwars = "true" autodeploy = "true"
Xmlvalidation = "false" xmlnamespaceaware = "false">
</Host>
<! -Virtual host configuration -->
<Host name = "http://www.cnblogs.com/" appbase = "webapps"
Unpackwars = "true" autodeploy = "true"
Xmlvalidation = "false" xmlnamespaceaware = "false">
<Context Path = "" docbase = "G: \ Dev \ apache-Tomcat-6.0.33 \ webapps \ killbug \ "DEBUG =" 1 "reloadable =" true "allowlinking =" true "> </context>
</Host>
</Engine>

Service. the When multiple hosts are configured, you cannot use an IP address as the host name to access tomcat. Because the host name value corresponds to the same IP address, you do not know which site to visit.

When creating a host name-based virtual host. in addition to configuring the ing between host names and sites in XML, you must also configure the ing between host names and IP addresses so that the Web server can be found in the network. You can configure the ing between the host name and the IP address in either of the following ways:

1. Configure through DNS (Domain Name Resolution Server) System

2. configure it in the local hosts file of the client.

Hosts files can be used for small enterprise intranets, while DNS is used for large network services (such as providing external services on the Internet ). The customer first finds the ing between the host name and IP address in the local hosts file. If not, the customer will go to the DNS system to find the ing.

The following describes the configuration in the hosts file.

Find the hosts file in c: \ windows \ system32 \ drivers \ etc. open the file with editplus and you will see 127.0.0.1 localhost by default. Why do we access http: // localhost: 8080/. Next we will write 127.0.0.1 www.cnblogs.com in a new line to establish the ing between 127.0.0.1 and www.cnblogs.com host names.

As shown in the figure above, we configured service. XML to complete the VM configuration. Start Tomcat and access the http://www.cnblogs.com: 8080/killbug to access the killbug site.

 

Conclusion: tomcat, as a container, needs to listen to HTTP messages, call the response servlet, and respond. This basic process seems to be just the tip of the iceberg of Tomcat. Let's move on.

----------------------------------------------------------------------

Hard work may fail, but not hard work will certainly fail.
Sharing

Related Article

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.