On the working principle of Tomcat good

Source: Internet
Author: User
Tags stringbuffer

Turn from: http://www.163ns.com/zixun/post/5224.html

A Web server is also called an HTTP server because it communicates with the client (that is, the browser) using the HTTP protocol. A Java-based Web server uses two important classes: Java.net.Socket and Java.net.ServerSocket, and the communication protocol uses HTTP. So, naturally, we'll talk about Web servers in the two classes of HTTP and Java. Then we'll introduce a simple Web server application.
One, HTTP (the Hypertext Transfer Protocol):

HTTP is a protocol that allows Web server and browser to send/receive over the Internet, which is a request/response protocol. The browser requests a file and the server responds to the request. HTTP TCP connection----The default port is the first release version of 80.Http is http/0.9, the current general use is Http1.1.
Through the HTTP protocol, usually the browser initiates a session transaction by establishing a connection and sending a request, the server responds to or gives a response to the browser, and the browser-side or server-side can terminate a connection prematurely in the session. For example, when you use a browser as a client, you can click the Stop button to terminate the file being downloaded, effectively shutting down the HTTP connection to the Web server side.
1.HTTP Request:
An HTTP request consists of the following 3 sections:
· Method-uri-protocal/version
· Request headers
· Entity body
An example of an HTTP request is as follows:
post/examples/default.jsp http/1.1
Accept:text/plain;text/html
Accept-language:en-gb
Connection:keep-alive
Host:localhost
user-agent:mozilla/4.0 (compatible; MSIE 4.01;windows 98)
Content-length:33
content-type:application/x-www-form-urlencoded
Accept-encoding:gzip,deflate
Lastname=franks&firstname=michael
Method-uri-protocal/version appears on the first line of the request, that is:
post/examples/default.jsp http/1.1
Where the post representation is the requested method,/examples/default.jsp on behalf of uri,http/1.1 represents Protocol/version.
HTTP1.1 supports seven kinds of request methods: Get, POST, head, OPTIONS, put, delete, and trace. Where get and post are most commonly used.
The URI completely describes the source file type, and a URI is usually relative to the server-side root directory. As a result, the path to the URI is usually such/*. A URL Uniform Resource Locator is usually a URI. The protocol version represents the HTTP version used.
The requested file header request header can reflect important information such as browser information and entities requested. For example, it contains the encoding used by the browser, the length of the entity, and so on. Each header is separated by the CRLF (carriage return/linefeed), and the CRLF is the carriage return line wrap.
There is a CRLF between the headers and the entity entities, which is important for the HTTP request format.
Crlf tells the HTTP server where the content of the request starts.
In the above HTTP request, the request entity is as follows:
Lastname=franks&firstname=michael
2.HTTP Response:
Similar to HTTP requests, an HTTP response consists of the following three parts:
· Protocol-status code-description
· Response headers
· Entity body
The following is an example of an HTTP response:
http/1.1 OK
server:microsoft-iis/4.0
date:mon,5 13:13:33 GMT
Content-type:text/html
last-modified:mon,5 13:13:12 GMT
content-length:112





Welcome to Brainy Software


The first line of the response is somewhat similar to the first line of the request format. It tells that the protocol is HTTP1.1, which requests a success sign of 200. And everything is fine OK. The message header of the response is similar to the message header of the request, and also contains some environment parameters. The same response message is separated by CRLF.
Second, the Socket class:

The socket is a port on a network connection. The socket allows the application to read/write to the data on the network. The two apps that are located on different computers can rely on sockets to receive/read data from each other, and you need to know their IP address and port number for the application software on one computer to send information to another computer. In Java, the socket class is the Java.net.Socket class.
To create a Socket object, you can construct the object in one of the many constructed methods of the class, one of which requires the host name and port number: The public Socket (java.lang.String host,int port). For example, to connect a yahoo.com with a port number of 80, you can write this: new Socket ("yahoo.com", 80).
The following code fragment creates a socket class, but communicates with native 127.0.0.1.
Socket socket = new Socket ("127.0.0.1", "8080");
OutputStream OS = Socket.getoutputstream ();
Boolean autoflush = true;
PrintWriter out = new PrintWriter (Socket.getoutputstream (), AutoFlush);
BufferedReader in = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
Send an HTTP request to the Web server side
Out.println ("get/index.jsp http/1.1");
Out.println ("host:localhost:8080");
Outprintln ("Connection:close");
Out.println ();
Read response
Boolean loop = true;
StringBuffer sb = new StringBuffer (8096);
while (loop) {
if (In.ready) {
int i=0;
while (I!=-1) {
i = In.read ();
Sb.append ((char) i);
}
}
loop = false;
}
Thread.CurrentThread (). Sleep (50);
Response results to the display platform
System.out.println (Sb.tostring ());
Socket.close ();
Third, ServerSocket class

The socket class represents the socket for client, which means that whenever you are connecting to a remote server, you can create a socket object. Now, if you want to create a server application, such as HTTP server or FTP server, you need to do it in a different way. This is because the server side is receiving requests from clients in real time.
ServerSocket is different from the socket. ServerSocket's role is to wait for the client's request. Once the ServerSocket receives a request from the client, a socket object is created to communicate.
To create a server socket, you need to use one of the four constructed methods provided by the ServerSocket class. You need to specify the IP address and the port number on which the server socket will be listening. Typically, the IP address will be 127.0.0.1, that is, the server socket will listen for the local machine. The IP address that the server socket is listening to is referred to as the binding address. Another important attribute of the server socket is backlog, which is the maximum queue length for incoming connection requests before the server socket starts rejecting incoming requests.
One of the ServerSocket classes is constructed as follows:
public ServerSocket (int port, int backLog, inetaddress bindingaddress);
For this construction method, the binding address must be an instance of the java.net.InetAddress. A simple way to construct a InetAddress object is to call its static method Getbyname and pass in a string containing the host name, just like the following code.
Inetaddress.getbyname ("127.0.0.1");
The following line of code constructs a serversocket that listens to the local machine 8080 port, and its backlog is 1.
New ServerSocket (8080, 1, inetaddress.getbyname ("127.0.0.1"));
Once you have a ServerSocket instance, you can have it wait for incoming connection requests on the port where the binding address and the server socket are listening. You can do this by invoking the Accept method of the ServerSocket class. This method only returns if there is a connection request, and the return value is an instance of the socket class. The socket object can then send a byte stream and accept the byte stream from the client application, as explained in the previous section, "Socket class." In fact, in the procedure that accompanies this chapter, the Accept method is the only method used
Iv. Application of examples
Our application includes the following three classes:
· Httpserver
· Request
· Response
The entry for the application (that is, the Main method) in the Httpserver class, the main method creates a Httpserver object and then calls its await method, which, like its name, listens to the given port, waits for the HTTP request, and receives the request, The response object is then returned. This method has been listening to the client's request until a shutdown command is closed.
This application not only sends static resources, such as HTML files, image images, and files in a folder, but also handles dynamically transmitted bytes. But it does not transmit any headers, such as dates, cookies, etc.
Let's take a look at these three classes in more detail.
Httpserver class
The Httpserver class is a server-side code, as shown in Listing 1.1. Listing 1.2 shows the await method in detail, not shown in Listing 1.1.
List1.1:httpserver class
public class httpserver{
/**
*web_root this path to place HTML files and some other files.
* In this package, Web_root is the working path "Webroot".
* The working path is the location called by the Java command in the file system.
*/
public static final String Web_root =
System.getproperty ("User.dir") +file.separator + "Webroot";
Close command
private static final String Shutdown_command = "/shutdown";
Receive Shutdown command
Private Boolean shutdown = false;
public static void Main (string[] args) {
Httpserver Server = new Httpserver ();
Server.await ();
}
public void await () {
...
}
}
The await method is detailed as follows:
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 wait Request
while (!shutdown) {
Socket socket = NULL;
InputStream input = null;
OutputStream output = null;
try{
Socket = Serversocket.accept ();
input = Socket.getinputstream ();
Output = Socket.getoutputstream ();
Create the Request object, and parse
Request Request = new request (input);
Request.parse ();
Creating response objects
Response Response = new Response (output);
Response.setrequest (Request);
Response.sendstaticresource ();
Close socket
Socket.close ();
To see if the URI is a closed URI
shutdown = Request.geturi (). Equals (Shutdown_command);
}catch (Exception e) {
E.printstacktrace ();
Continue
}
}
}
This WEB server can access all the web_root directories and the static resources under the subdirectories, Web_root initialized as follows: public static final String Web_root =
System.getproperty ("User.dir") +file.separator + "Webroot";
The code contains a directory called Webroot, which has some static resources under it. To access the static resources under the server, the URL can be written like this: http://machineName:port/ StaticResource. If it is a cross machine access, then MachineName is the computer's name or IP address, if the same machine, then the localhost or the computer name, the port is 8080,staticresource is the name of the file you will access, but the file must Under the Web_root directory.
For example, if you are accessing the same machine through the server, access the index.html file for the service, the URL is: http://localhost:8080/index.html.
If you want to turn off the service, you can enter a URL path that you have set up in advance in your program on the browser. For example, to stop the currently running service, the shutdown command in our example is controlled by the static constant SHUTDOWN in the Httpserver class, the private static final String Shutdown_command = "/ SHUTDOWN ", so we want to close the example of the service, the URL can be written like this: Http://localhost:8080/SHUTDOWN.
Now, let's look at the await method. This method name is await rather than wait, mainly because there is a method name for multithreading in Java.lang.Object this superclass called wait. The await method initially creates a ServerSocket object and then makes a while loop.
ServerSocket = new ServerSocket (port, 1, Inetaddress.getbyname ("127.0.0.1"));
Loop waiting for request requests
while (!shutdown) {...}
In the loop code, when there is an HTTP request on port 8080, ServerSocket returns a socket object via the Accept method, that is, the socket = Serversocket.accpet ().
Request class:
This class represents an HTTP request object. The request object instantiates a InputStream object that needs to pass a socket object. You can call the Read method of the InputStream object to obtain the data transmitted by the HTTP request object.
The specific contents of the class are as follows listing 1.3. The class contains two methods, parse methods (listing 1.4) and GetURI (listing 1.5) methods.
Listing 1.3:
public class Request {
private InputStream input;
Private String URI;
Public Request (InputStream input) {
This.input = input;
}
Public String GetURI () {
return URI;
}
public void Parse () {
......
}
private string Parseuri (string requeststring) {
......
}
}
Listing 1.4:
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; Jrequest.append ((char) buffer[j]);
}
System.out.print (Request.tostring ());
URI = Parseuri (request.tostring ());
}
The parse method resolves the data that the request object transmits. This method has no other way, just to get the URL path in the HTTP request. The following GetURI method returns the URL path.
Listing 1.5:
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;
}
Response class:
The class is as follows:
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" +
"Content-type:text/html\r\n" +
"Content-length:23\r\n" +
"\ r \ n" +
"File not Found";
Output.write (Errormessage.getbytes ());
}
}catch (Exception e) {
If the file object cannot be instantiated, an exception is thrown
System.out.println (E.tostring ());
}finally {
if (fis!=null)
Fis.close ();
}
}
}
The first thing you notice is that you get the Java.io.OutputStream object through the constructor, as follows:
Public Response (OutputStream output) {
This.output = output;
}
Run this application:
Enter address on the browser address bar: http://localhost:8080/index.html, you can see the test page.
If you enter a file address that does not exist, the http://localhost:8080/indexs.html is as follows, and a 404 error is returned.

Article Source: http://www.163ns.com, reprint please specify.

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.