How Java Web servers work

Source: Internet
Author: User
Tags rfc

By Budi kurniawan translated by javafuns

04/23/2003

Edit annotation:This article is adapted from BudiPublished by myself about TomcatBooks on internal implementation principles.You can find more information on his website.

WebThe server is also called the Hypertext Transfer Protocol (HTTP) server because it uses the HTTP protocol to communicate with the client. It usually refers to Web browsers. Java-based Web servers use two important classes,java.net.SocketAndjava.net.ServerSocketTherefore, this article first discusses the HTTP protocol and the two classes. Then, I will explain a simple web server program included in this book.

The Hypertext Transfer Protocol (HTTP)

HTTP enables the WebServersAnd the browser sends and receives data over the Internet. it is a request-response protocol-when a client initiates a request, the server responds to the request. HTTP uses a trusted TCP connection. By default, port 80 of TCP is used. the first version of HTTP is HTTP/0.9, followed by HTTP/1.0. the current version is HTTP/1.1 defined by RFC 2616(scheme.

This section briefly introduces HTTP 1.1, which helps you understand the messages sent by web server applications. If you are interested in more details, read RFC 2616.

When using HTTP, the Client Always starts a transaction by establishing a connection, and then sends an HTTP request. the server does not actively contact the client or establish a callback to connect to the client (is in no position to contact a client or to make a callback connection to the client ). both the client and server can abort a connection in advance. for example, when using a Web browser, you can click the stop button on the browser to end the file download process, effectively closing the HTTP connection with the Web server.

HTTP requests

An HTTP request consists of three parts:

  • Method-Uri-Protocol/version

  • Request headers

  • Entity body

An example of an HTTP request is as follows:

POST /servlet/default.jsp HTTP/1.1
Accept: text/plain; text/html
Accept-Language: en-gb
Connection: Keep-Alive
Host: localhost
Referer: http://localhost/ch8/SendDetails.htm
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-Protocol/version appears in the 1st rows of the request.

POST /servlet/default.jsp HTTP/1.1

POSTIs the request method,/servlet/default.jspUri,HTTP/1.1Is the value of Protocol/version.

Each HTTP request can use any of the following methods:GET,POST,HEAD,OPTIONS,PUT,DELETE, AndTRACE.GETAndPOSTIs the two most common requests in Internet programs.

Uri completely specifies an Internet resource. Uri is usually parsed relative to the root directory of the server. Therefore, it should always/ Start. Url is actually a type of Uri. The Protocol version indicates the version number of the HTTP protocol in use.

The request header contains useful information about the client environment and request body, such as the browser language settings and length of the Request body. Each request header is separated by the CRLF sequence.

There is a very important blank line (CRLF sequence) between the header and the subject ). this line marks the beginning of the Request body. some Internet programming books hold that this CRLF is part of 4th HTTP requests.

In the previous HTTP request, the request subject is simply one line as follows:

LastName=Franks&FirstName=Michael

In a typical HTTP request, the request subject can be longer than this.

HTTP responses

Similar to a request, an HTTP response is composed of three parts:

  • Protocol-status code-Description

  • Response Headers

  • Entity body

The following is an example of an HTTP response:

HTTP/1.1 200 OK
Server: Microsoft-IIS/4.0
Date: Mon, 3 Jan 1998 13:13:33 GMT
Content-Type: text/html
Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT
Content-Length: 112

<title>HTTP Response Example</title>Welcome to Brainy Software
</body>

The first line of the response header is similar to the first line of the request header. the first line tells you that the protocol used is HTTP Version 1.1. The request is successful (200 = success) and everything is correct.

Similar to the request header, the Response Header also contains useful information. The response body is HTML content. The header and body are also separated by the crlfs sequence.

The socket class

A socket is an endpoint of a network connection. the socket allows the program to read data from the network and send data to the network. two programs on two different machines can communicate by sending and receiving byte streams at one connection. to send a message to another program, you must know its IP address and its socket port.JavaSocket usage injava.net.SocketClass.

To create a socket, you can useSocketOne of the constructors of the class accepts the host name and port number:

public Socket(String host, int port)

hostIs the remote machine name or IP address,portIs the port number of the remote program. For example, to connect port 80 of Yahoo.com, you should build the socket as follows:

new Socket("yahoo.com", 80);

Once you have successfully createdSocketClass, you can use it to send and receive byte streams. When sending byte streams, you must first callSocketClassgetOutputStreamMethod acquisitionjava.io.OutputStreamObject. When sending text to a remote programOutputStreamConstructjava.io.PrintWriterObject. To receive byte streams from the other end, you must callSocketClassgetInputStreamMethod to obtainjava.io.InputStream Object.

The following code snippet establishes a socket to communicate with the local HTTP server (127.0.0.1 means a local host), sends an HTTP request, and receives a response from the server. It createsStringBufferThe object contains the response content and then prints it to the console.

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
out.println("GET /index.jsp HTTP/1.1");
out.println("Host: localhost:8080");
out.println("Connection: Close");
out.println();

// read the 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);
}

// display the response to the out console
System.out.println(sb.toString());
socket.close();

To get the correct response from the Web server, you must send an HTTP request following the HTTP protocol. if you have read the previous section "The Hypertext Transfer Protocol (HTTP)", you will understand the HTTP requests in the code above.

The ServerSocketClass

SocketClass represents a "client" ("client") socket, which is the socket built when you want to connect to a remote server program. if you want to implement a server program, such as HTTP server or FTP server, you need a different method. this is because your server must be persistent and ready to receive requests at any time, because it does not know when a client program will connect to it.

For this reason, you must usejava.net.ServerSocketClass. This is an implementation of the server socket. The server socket waits for the connection request from the client. Every time it accepts the connection request, it createsSocketInstance location and client communication.

To create a server socket, you must useServerSocketOne of the four constructors provided by the class. you need to specify the IP address and the port number of the server socket listener. generally, the IP address is 127.0.0.1, which means that the server socket will listen on the local machine. the IP address of the server socket is also called the binding address. another important attribute of the server socket is its backlog, which refers to the maximum length of the Connection Request queue that can be tolerated before the server socket begins to reject new requests.

ServerSocketOne of the constructors of the class has the following method declaration:

public ServerSocket(int port, int backLog, InetAddress bindingAddress);

For this constructor, the binding address must bejava.net.InetAddress An instance. A simple constructionInetAddressThe object is called through its static method.getByName, Pass a string containing the host name to it:

InetAddress.getByName("127.0.0.1");

The following line of code constructsServerSocket, Listen toPort 8080, and the backlog value is set to 1.

new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));

Once you haveServerSocketInstance, you can call itacceptThe method tells it to wait for the connection request to enter. This method will only be returned when there is a connection request. It returnsSocketClass instance. ThisSocketThe object can then be used to send and receive byte streams from the client program, as explained in the socket class. In fact, in the program included in this articleacceptThe method is the only method used.

The Application

Our web server program is located in the packageex01.pyrmont, By3Classes:

  • HttpServer

  • Request

  • Response

The staticmainMethod) inHttpServerClass. It createsHttpServerInstance and call itsawaitMethod. As the name impliesawaitWait for the HTTP request, process the request, and send a response to these clients. It will wait until it receives a close command. (The method name is usedawaitInsteadwaitBecausewaitYesSystem.ObjectA very important method for processing multithreading .)

This program only sends static resources from the specified directory, such as HTML and image files. It does not support headers (such as time or cookies ).

Now, let's take a look at these three classes in the next chapter.

The HttpServerClass

HttpServerClass represents a Web server, which can be provided inWEB_ROOTThe static resources found in the Directory and the static resources under all subdirectories in the directory.WEB_ROOTPerform initialization as follows:

public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "webroot";

The above code containsWebrootDirectory, including some static resources used to test this program. You will also find a servlet, which will be used in my next article, "How servlet containers work ."

To request a static resource, enter the following URL in your browser address bar:

http://machineName:port/staticResource

If you run your program and send a request on another machinemachineNameIs the name or IP address of the computer that runs the program. If your browser is on the same machine, you can uselocalhostAsmachineNameThe. Port is 8080,staticResourceIs the name of the file to be requested, and the file must be located inWEB_ROOT.

For example, if you use the same computer to test the program and you wantHttpServerReturnIndex.htmlFile, using the following URL:

http://localhost:8080/index.html

To stop the server, enter the pre-defined closed string in the address bar to send the close command.HttpServerClass is definedSHUTDOWNStatic final variable:

private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";

To disable the server, you can use:

http://localhost:8080/SHUTDOWN

Now let's take a look atawaitMethod. The explanation of the Code is following this listing.

Listing 1.1.HttpServerClass'awaitMethod

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;
}
}
}

awaitCreateServerSocketInstance, and then enterwhileLoop.

serverSocket =  new ServerSocket(
port, 1, InetAddress.getByName("127.0.0.1"));

...

// Loop waiting for a request
while (!shutdown) {
...
}

While loop inServerSocket Ofaccept Stop at MethodThis method returns a socket object only when an HTTP request is received on port 8080:

socket = serverSocket.accept();

After receiving a request,awaitMethod slave

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.