Implementing Web Servers in Java

Source: Internet
Author: User
Tags format flush header connect socket string version thread

The function principle of HTTP protocol

WWW is an application system with Internet as transmission medium, the most basic transmission unit of WWW is Web page. The work of WWW is based on the client/server computing model, consisting of a Web browser (client) and a Web server (server), which communicates with a Hypertext Transfer Protocol (HTTP). The HTTP protocol, which is based on TCP/IP protocol, is an application layer protocol between Web browsers and Web servers, and is a universal, stateless, object-oriented protocol. The principle of the HTTP protocol includes four steps:

(1) Connection: A Web browser establishes a connection with a Web server, opens a virtual file called a socket (socket), which marks the successful connection establishment.

(2) Request: The Web browser submits the request to the Web server via the socket. HTTP requests are typically a GET or post command (the post is used for the pass of form parameters). The format of the Get command is:

Get path/filename http/1.0

The filename indicates the file being accessed, and http/1.0 indicates the HTTP version used by the Web browser.

(3) Reply: After the Web browser submits the request, it is routed to the Web server via the HTTP protocol. When the Web server receives the transaction, the processing results are returned to the Web browser via HTTP, which displays the requested page in the Web browser.

For example: Assuming the client has established a connection with www.mycompany.com:8080/mydir/index.html, the Get command is sent: Get/mydir/index.html http/1.0. A Web server with host name www.mycompany.com searches its document space for Mydir file index.html of subdirectories. If the file is found, the Web server transmits the contents of the file to the appropriate Web browser.

To tell the Web browser what type of content to transfer, the Web server first transmits some HTTP header information and then transmits the specific content (that is, the HTTP body information), separating the HTTP header information from the HTTP body information with a blank line.
The common HTTP header information is:

①http 1.0 OK

This is the first line answered by the Web server, listing the HTTP version number and the answer code that the server is running. The code "OK" indicates that the request is complete.

②mime_version:1.0

That indicates the version of the MIME type.

③content_type: Type

This header information is very important and it indicates the MIME type of the HTTP body information. Such as: Content_type:text/html indicates that the transmitted data is an HTML document.

④content_length: Length Value

It indicates the length (in bytes) of the HTTP body information.

(4) Close the connection: When the answer is complete, the Web browser and the Web server must be disconnected to ensure that other Web browsers can establish a connection with the Web server.

Second, Java implementation of Web server functions of the program design

According to the principle of the HTTP protocol mentioned above, the method of implementing the Web server program of Get request is as follows:

(1) Create the ServerSocket class object and listen for port 8080. This is for the purpose of distinguishing from HTTP's standard TCP/IP port 80;

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

(3) Creating the input stream instream and output stream outstream associated with the socket word;

(4) reads the request information submitted by a line of clients from the input stream instream associated with the socket, and the request information is in the format: Get path/filename http/1.0

(5) Obtain the request type from the request information. If the request type is get, the access HTML file name is obtained from the request information. When there is no HTML file name, the index.html is used as the filename;

(6) If the HTML file exists, open the HTML file, pass the HTTP header information and the HTML file contents back to the Web browser via the socket, and then close the file. Otherwise send the error message to the Web browser;

(7) Closes the socket word that is connected to the appropriate Web browser.

The following program is a multithreaded Web server written according to the above methods to ensure that multiple clients can connect to the Web server at the same time.

Program 1:webserver.java files
Webserver.java Web Server in Java
Import java.io.*;
Import java.net.*;
public class 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 a client's connection request
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 Web browser's socket word
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 request information submitted by Web browser
System.out.println ("Received:" +inline);
if (getrequest (inline)) {//If a GET request
String filename=getfilename (inline);
File File=new file (filename);
if (file.exists ()) {//If the file exists, send the file to the Web browser
SYSTEM.OUT.PRINTLN (filename+ "requested.");
Outstream.println ("http/1.0 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= "<body>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++;}//Latency
Client.close ();
catch (IOException e) {
System.out.println ("Exception:" +e);
}
}

/* Obtain 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 filename 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 (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 line in the program Cheng Zi class is used to parse a request submitted by a Web browser and return the answer message to a Web browser. where the Getrequest () method detects whether the customer's request is "get", and the GetFileName (s) method obtains the HTML file name to be accessed from the customer request information S; Sendfile () method to pass the specified file contents back to the Web browser via a socket.

The Getrequest () method and related parts of the above program can also be modified to handle the POST request.

Iii. Running Examples

To test the correctness of the above program, place the compiled Webserver.class, Connectionthread.class, and index.html files in the same directory on one of the hosts in the network (for example, the C:\JWEB directory of the host nt40srv).

Program 2:index.html files
<HTML>
<HEAD>
<meta http-equiv= "Content-type" content= "text/html; Charset=gb_2312-80 ">
<title>java Web Server </TITLE>
</HEAD>
<BODY>
August 28, 1998
</BODY>
</HTML>
First run the Webserver.class on this host with the Java command:
C:\jweb>java webserver

Then run the browser software on the client, enter the URL address (such as: http://nt40srv:8080/index.html) of the webserver program at the URL, and display the specified HTML document in the browser window.

Note that you cannot have the default port number 8080, such as the default, to run a normal Web server for that host.

Note that you can test on a stand-alone computer with Windows 95 installed without a network condition by using localhost or 127.0.0.1 instead of the domain name portion of the URL address, that is, the URL address is http://localhost:8080.

  please contact the site, timely note your name. Contact Email: edu#chinaz.com (change # to @).



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.