Use Java to implement web servers

Source: Internet
Author: User
Tags sendfile

Use Java to implement web servers
 
I. Principle of the HTTP protocol

The principle of HTTP protocol includes four steps:

1. connection: the Web browser establishes a connection with the Web server. 2. Request: the Web browser submits a request to the Web server through socket. 3. Response: After the web browser submits a request, the request is sent to the Web server over HTTP. After receiving the request, the Web server processes the transaction and returns the result to the Web browser over HTTP, so that the requested page is displayed on the web browser. 4. link connection: After the response is completed, the web browser and the Web server must be disconnected to ensure that other Web browsers can establish a connection with the Web server.

2. Use Java to implement Web Server programming

Based on the principle of the above HTTP protocol, the method for implementing the GET request web server program is as follows:

1. Create a serversocket object and listen to port 8080. This is different from HTTP's standard TCP/IP Port 80; 2. wait and accept the client to connect to port 8080 to obtain the Socket connected to the client; 3. create the input stream instream and output stream outstream associated with the socket;
Format: Get path/File Name HTTP/1.0; 4. read the request information submitted by a client from the input stream instream associated with the socket. The request information format is: Get path/File Name HTTP/1.0; 5. obtain the request type from the request information. If the request type is get, the accessed HTML file name is obtained from the request information. If there is no HTML file name, index.htm 1 is used as the file name; 6. if an HTML file exists, open the HTML file, return the HTTP header information and HTML file content to the Web server through socket, and then close the file. Otherwise, an error message is sent to the Web browser. close the socket word connected to the corresponding web browser.

The following program is compiled based on the above method to implement a multi-threaded web server to ensure that multiple clients can connect to the Web server at the same time.

// Webserver. Java write web server in Java

Import java. Io .*;

Import java.net .*;

Import java. util. date;

Public class webserver {

Public static void main (string ARGs [])

{

Int I = 1, Port = 8080;

Serversocket Server = NULL;

Socketclient = NULL;

Try {

Server = new serversocket (port );

System. Out. println

("Web server is listening on port"

+ Server. getlocalport ());

For (;;){

Client = server. Accept ();

// Accept client connection requests

New connection thread (client, I). Start ();

I ++;

}

} Catch (exception e) {system. Out. println (E );}

}

}

/* Connnection Thread class completed

Communication with a Web browser */

Class connection thread extends thread {

Socket Client; // The socket character used to connect to the Web browser

Int counter; // counter

Public connection thread (socketcl, int c ){

Client = Cl;

Counter = C;

}

Public void run () // thread body

{

Try {

String response IP = client. getinetaddress (). tostring ();

// Client IP Address

Int destport = client. getport ();

// Client port number

System. Out. println

("Connecction" + counter + ":

Connected to "+ destip +" on port

"+ Destport + ".");

Printstream outstream = new printstream

(Client. getooutputstream ());

Datainputstreaminstream + 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, the file is sent to the Web browser.

System. Out. println (filename + "requested .");

Outstream. println ("HTTP/1.0200ok ");

Outstream. println ("mime_version: 1.0 ");

Outstream. println ("content_type: text/htm1 ");

Int Len = (INT) file. Length ();

Outstream. println ("content_length:" + Len );

Outstream. println ("");

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

Outstream. Flush ();

} Else {// when the file does not exist

String notfound = "htmlheadtitle

Not found/Title/head

BodyhlError404-File notfound

/HL/body/html ";

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

{

If (S. substring (0, 3). Then signorecase

("Get") return true;

}

Return false;

}

/* Get the name of the file to be accessed */

String getfilename (string s ){

String F = S. substring (S. indexof (/) + 1 );

F = f. substring (0, F. indexof (/));

Try {

If (F. charat (0) = /)

F = f. substring (1 );

} Catch (string indexoutofboundsexception 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 ){

Try {

Datainputstreamin = 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 connection thread sub-class in the program is used to analyze the requests submitted by a Web browser and return the response information to the Web browser. The getrequest () method is used to check whether the customer's request is "get"; the getfilename (s) method is to obtain the HTML file name to be accessed from the customer's request information s; sendfile () method to send the specified file content back to the Web browser through socket.

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.