Java-based web server work mechanism (3)

zhaozj2021-02-16  61

REQUEST class

The REQUEST class represents an HTTP request. Socket Processing the client's communication, returns an InputStream object, and can construct an instance of a Request class by passing the object. The raw data of this HTTP request is obtained by calling the Read method of the InputStream object (RAW DATA).

Request has two public methods: Parse and Geturi. The PARSE method explains the original data of the HTTP request. It doesn't do a lot of things - it is only the only information that is only HTTP requests, which is from private method PARSEURI. The Parseuri method saves the URI to the URI variable and then calls the public method geturi to return an HTTP request URI.

In order to understand how the Parse and Parseuri methods work, you need to know the internal structure of the HTTP request. This structure is defined in the RFC2616 document.

An HTTP request contains three parts:

Request Line requests Baotou (Message Body)

Now, we are only interested in Request Line only on the first part of the HTTP request. A request row started by the method tag, the URI and protocol version requested after the rear root, and finally end by the CRLF character. The elements in the request row are separated by space characters. For example, the requested line of the index.html file requested by the GET method is as follows:

Get /Index.html http / 1.1 // This is a request line

Method Parse reads the entire byte stream from the Socket's InputStream, which is the request object passed, then Parse stores these byte streams in a buffer, and assembles a StringBuffer called Request in the buffer. Object.

The following listing 1.2. Shows the usage of the Parse method:

Listing 1.2. The Request Class' PARSE METHOD

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

Request.Append ((char) buffer [j]);

}

System.out.print (Request.toString ());

URI = PARSEURI (Request.toString ());

}

The Parseuri method gets the URI from the request line. Listing 1.3 shows the use of the Parseuri method. The first and second spaces in the Parseuri reduced request are used to get the URI.

Listing 1.3. The Request Class' PARSEURI METHOD

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

Response represents an HTTP response. Its constructor accepts an OutputStream object, such as:

Public response (OutputStream output) {

THIS.output = OUTPUT;

}

The Response object is constructed by the AWAIT method of the HTTPServer class, which is passed to the OutputStream object you get from Socket.

The Response class has two public methods: SetRequest and SendStaticResource. SetRequest method passed an REQUEST object to the Response object. The code in Listing 1.4 shows this:

Listing 1.4. The Response Class' SetRequest Method

Public void setRequest (Request request) {

THIS.REQUEST = REQUEST;

}

The SendStaticResource method is used to send a static resource, such as an HTML file. Listing 1.5 gives its implementation process:

Listing 1.5. The Response Class' SendStaticResource Method

Public void sendstaticResource () throws oException {

BYTE [] bytes = new byte [buffer_size];

FileInputStream Fis = NULL;

Try {

File file = new file (httpserver.web_root, request.geturi ());

IF (file.exiss ()) {

FIS = New FileInputStream (File);

INTCH = 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) {

// thrown if cannot instantiate a file object

System.out.println (E.TOString ());

}

Finally {

IF (FIS! = NULL)

fis.close ();

}

}

The SendStaticResource method is very simple. It first passes the parent path and the sub-path to the File class constructor, which is instantiated to the Java.IO.File class. File file = new file (httpserver.web_root, request.geturi ());

Then it checks if the file exists. If there is, the SendStaticResource method constructs a java.io.fileInputStream object by passing the File object. Then call the FileInputStream's Read method to write the byte stream as to OutputStream output. Note that the content of the static resource is also sent to the browser as the original data.

IF (file.exiss ()) {

FIS = New FileInputStream (File);

INTCH = fis.read (bytes, 0, buffer_size);

While (ch! = -1) {

Output.write (Bytes, 0, CH);

CH = fis.read (bytes, 0, buffer_size);

}

}

If this file does not exist, the SendStaticResource method sends an error message to the browser.

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 ());

Compile and run applications

To compile and run applications, you first need to decompress the .zip file containing this application application. The directory you decompressed becomes Working Directory, which has three subdirectories: SRC /, CLASSES /, and LIB /. To compile the application, you need to enter the following statement in the working directory:

Javac -d. SRC / EX01 / PYRMONT / *. Java

This -d option parameter writes the result to the current directory instead of the src / directory.

To run an application, enter the following statement in the working directory:

Java EX01.PYRMONT.HTTPSERVER

To test your app, open your browser, enter the following URL in the address bar:

Http: // localhost: 8080 / index.html

You will be able to see the index.html page shown in your browser, as shown in Figure 1.

Figure 1. The Output from the Web Server

In the console, you can see the following:

Get /index.html http / 1.1

Accept: * / *

Accept-language: EN-US

Accept-encoding: Gzip, deflate

User-agent: mozilla / 4.0 (compatible; msie 4.01; windows 98)

Host: Localhost: 8080

Connection: Keep-alive

Get /Images/logo.gif http / 1.1

Accept: * / *

Referr: http: // localhost: 8080 / index.html

Accept-language: EN-US

Accept-encoding: Gzip, deflate

User-agent: mozilla / 4.0 (compatible; msie 4.01; windows 98) Host: localhost: 8080

Connection: Keep-alive

Summary summary

In this article, you understand a simple WEB server's work mechanism. The application source code included in this article contains only three classes, but not all are useful. Despite this, it can also be served as a good learning tool.

Translated by Willpower, 2003.11.24

转载请注明原文地址:https://www.9cbs.com/read-24925.html

New Post(0)