How to implement a web server (turn ->) with Java

xiaoxiao2021-03-06  41

First, the principle of the role of the HTTP protocol

WWW is an application system as a transmission medium in an Internet, and the most basic transmission unit on the WWW online is a web page. WWW's work is based on client / server computing models, composed of a web browser (client) and web server (server), and the hypertext transfer protocol (HTTP) is communicated between the two. The HTTP protocol is based on protocols above the TCP / IP protocol, which is an application layer protocol between web browses and web servers, which is a general, stateless, object-oriented protocol. The principle of the role of the HTTP protocol consists of four steps:

(1) Connection: The web browser establishes a connection to the web server, open a virtual file called Socket (socket), and the establishment of this file flag is successful.

(2) Request: The web browser submits a request to the web server via Socket. The request of HTTP is generally the GET or POST command (POST is used for the transfer of the FORM parameter). The format of the GET command is:

Get path / file name HTTP / 1.0

The file name indicates the files accessed, and HTTP / 1.0 pointers the HTTP version used by the web browser.

(3) Available: After the web browser submits the request, transfer to the web server via the HTTP protocol. After the web server is connected, transaction processing, the processing result is sent back to the web browser via HTTP, so that the requested page is displayed on the web browser.

Example: Assume that the client has established a connection with www.mycompany.com:8080/mydir/index.html, it will send a get command: get /mydir/index.html http / 1.0. The host named WWW.MYCOMPANY.COM Search subdirectory MyDir file index.html from its documentation space. If you find this file, the web server transmits the content to the corresponding web browser.

In order to inform the web browser, the web server first transmits some HTTP header information, then transmits the specific content (ie HTTP body information), and HTTP header information and HTTP body information are separated from one space.

Common HTTP headers are:

1 http 1.0 200 ok

This is the first line of the web server response, lists the HTTP version number and response code that the server is running. The code "200 ok" indicates the completion of the request.

2 MIME_VERSION: 1.0

It indicates the version of the MIME type.

3 Content_Type: Type

This header is very important, it indicates the MIME type of HTTP information. Such as: content_type: text / html indicates that the transferred data is an HTML document.

4 Content_length: length value

It indicates the length (bytes) of HTTP information.

(4) Turning the connection: When the response is completed, the web browser and the web server must be disconnected to ensure that other web browsers can connect with the web server.

Second, Java implementation of web server function programming

According to the principles of the above HTTP protocol, the method of implementing the web server program for GET request is as follows:

(1) Create a ServerSocket class object and listen to port 8080. This is taken to distinguish between the standard TCP / IP port 80 of HTTP;

(2) Wait, accept the client to connect to the port 8080 to get the socket connected to the client;

(3) Creating the input stream INSTREAM and output stream of the Socket word;

(4) Read the request information submitted by a line client from the input stream INSTREAM associated with the socket, the format of the request information is: GET path / file name HTTP / 1.0

(5) Get the request type from the request information. If the request type is GET, get the HTML file name accessed from the request information. When there is no HTML file name, use index.html as a file name; (6) If the HTML file exists, open the HTML file, transfer the http header information and the HTML file content to the web browser via the Socket, and then close the file. Otherwise send an error message to a web browser;

(7) Close the Socket word connected to the corresponding web browser.

The following program is written in accordance with the above method, which enables multi-threaded web servers to ensure that multiple clients can connect to the web server.

Program 1: WebServer.java file

//Webserver.java Write a web server with Java

Import java.io. *;

Import java.net. *;

Public clas Webserver {

Public static void main (string args []) {

INT i = 1, port = 8080;

Serversocket Server = NULL;

Socket client = NULL;

Try {

Server = new serversocket (port);

System.out.println ("Web Server IS Listening On Port" Server.getlocalPort ());

For (;;) {

Client = server.accept (); // Accept the connection request of the client

New Connectionthread (Client, i) .Start ();

i ;

}

} Catch (Exception E) {system.out.println (e);

}

}

/ * ConnnectionThread class completes communication with a web browser * /

Class Connectionthread Extends thread {

Socket client; // Connect the Socket word for web browser

INT Counter; // counter

Public ConnectionThread (socket cl, int C) {

Client = CL;

Counter = C;

}

Public void run () // thread body

{

Try {

String destip = client.getinetaddress (). TOSTRING (); // Client IP address

INT Destport = client.getport (); // Client port number

System.out.println ("Connection" Counter ": Connected to" Destip "On Port" Destport ";

PRINTSTREAM OUTSTREAM = New PrintStream (Client.getOutputStream ());

DataInputStream Instream = New DataInputStream (Client.getInputStream ());

String inline = instream.readline (); // read the request information submitted by the web browser

System.out.println ("received:" inline);

IF (getRequest (inline)) {// If it is a get request

String filename = getFileName (inline);

File File = New File (filename);

IF (file.exists ()) {// If the file exists, give the file to the web browser system.out.println (filename "requested.");

Outstream.println ("HTTP / 1.0 200 OK");

OutStream.println ("MIME_VERSION: 1.0");

OutStream.println ("Content_Type: Text / HTML");

INT LEN = (int) file.length ();

Outstream.println ("Content_length:" LEN);

Outstream.println ("");

Sendfile (outstream, file); // Send a file

Outstream.flush ();

} Else {// file does not exist

String notfound = "

Error 404-File Not Found

"

Outstream.println ("http / 1.0 404 no found");

OutStream.println ("Content_Type: Text / HTML");

Outstream.println ("Content_length:" NOTFOUND.LENGTH () 2);

Outstream.println ("");

Outstream.println (Notfound);

Outstream.flush ();

}

}

LONG M1 = 1;

While (m1 <11100000) {m1 ;} // delay

Client.Close ();

} catch (ioexception e) {

System.out.println ("Exception:" E);

}

}

/ * Get the request type is "get" * /

Boolean getRequest (string s) {

IF (S.Length ()> 0)

{

IF (s.Substring (0, 3). Equalsignorecase ("get")) Return True;

}

Return False;

}

/ * Get the file name to be accessed * /

String getFilename (string s) {

String f = s.substring (sindexof ('') 1);

f = f.substring (0, F.indexOf (''));

Try {

IF (F.Charat (0) == '/')

f = f.substring (1);

} catch (stringIndexoutofboundsexception e) {

System.out.println ("Exception:" E);

}

IF (F. Equals (")) f =" index.html ";

Return F;

}

/ * Send the specified file to the web browser * /

Void Sendfile (PrintStream outs, file file) {

Try {

DataInputStream IN = New DataInputStream (New FileInputStream (file));

INT LEN = (int) file.length ();

BYTE BUF [] = new byte [len];

IN.Readfully (BUF);

Outs.write (BUF, 0, LEN);

Outs.flush (); in.close ();

} catch (exception e) {

System.out.println ("Error Retrieving File.");

System.exit (1);

}

}

}

The ConnectionThread thread subclass in the program is used to analyze a request submitted by a web browser and pass the response information back to the web browser. Among them, the getRequest () method is used to detect whether the customer's request is "get"; the getFileName (s) method is to obtain the HTML file name to be accessed from the customer request information S; sendFile () method to pass the specified file content via Socket Give a web browser.

Modifications to the getRequest () method of the above program and related parts can also be processed.

Third, run an example

In order to test the correctness of the program, the compiled webserver.class, connectionthread.class, and the following index.html file are placed in the same directory of a host of the network (such as the host NT40SRV C: / jweb directory).

Program 2: Index.html file

This is the web server home page written in Java

August 28, 1998

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

First, use the java command on this host to run WebServer.class:

C: / jweb> Java Web Server

Then enter the browser software in the client, and enter the URL address to which the Webserver program belongs (such as http: // nt40srv: 8080 / index.html) will appear at the URL, and display the specified HTML document in the browser window.

Note that the port number 8080 cannot be default, such as default, run the normal web server.

Explanation, no network conditions can be tested on a single machine installed on Windows 95, the method is used to replace the domain name part of the URL address with localhost or 127.0.0.1, ie the URL address is http: // localhost: 8080.

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

New Post(0)