Implement HTTP Server 2 Based on Java

Source: Internet
Author: User

In the previous article, we introduced the basic knowledge of the HTTP protocol, as well as two important classes in Java: socket and socketserver. Next we will mainly introduce how to implement a Java-based HTTP server.

The HTTP server consists of three classes: httpserver, request, and response. The program entry is in the httpserver class, which calls the await () method so that the server starts waiting for the client connection. After the client connects, it will send static page content to the client browser. These three classes are described as follows:
1: httpserver class
Httpserver requires a root directory of the server defined in the web_root variable:
Public static final string web_root = system. getproperty ("user. dir ") + file. separator + "webroot"; when running the server, you can use the-D option to specify the environment variable user. dir value. The most important method in this class is the await () method. The content is as follows:
Public void await (){
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;
}
}
}
Construct a serversocket instance in the await () method. getinputstream () is passed to the request class for parsing, And the socket. getoutputstream () is passed to the response class, then the request object is passed to the response, and then the response is called. the sendstaticresource () method sends data to the client. After socket. Close (), check whether the command to close the server is received. If yes, exit the loop and end the program.

2. Request class
The main purpose of the request class is to encapsulate HTTP requests. It has an inputstream type parameter constructor.
Public request (inputstream input ){
This. Input = input;
}
At the same time, it also has an important string type member variable URI. The request aims to extract the URI from inputstream, which is implemented by two functions.
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 <I; j ++ ){
Request. append (char) buffer [J]);
}
System. Out. Print (request. tostring ());
Uri = parseuri (request. tostring ());
}

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;
}
The parseuri (string request) method is a private method. It parses the string parameter and returns the string between two spaces. This follows the HTTP request definition rules, if you do not know, refer to implementing one of the HTTP servers based on Java.

2. Response class
Two important member variables of response are output and requeset requests of the outputstream type. The function of this class is to get the URI from the request instance, then, add web_root to get the absolute path of the file, and then read the content of the file and write it to the socket. getoutputstream.
Public void sendstaticresource () throws ioexception {
Byte [] bytes = new byte [buffer_size];
Fileinputstream FCM = NULL;
Try {
File file = new file (httpserver. web_root, request. geturi ());
If (file. exists ()){
FS = new fileinputstream (File );
Int CH = FCM. Read (bytes, 0, buffer_size );
While (Ch! =-1 ){
Output. Write (bytes, 0, CH );
Ch = FCM. 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" +
"<H1> file not found Output. Write (errormessage. getbytes ());
}
}
Catch (exception e ){
// Thrown if cannot instantiate a file object
System. Out. println (E. tostring ());
}
Finally {
If (FS! = NULL)
FCM. Close ();
}
}

The following describes how to run this application. First, you can obtain the source code from the following address: javaslib webrootwhich contains an index.html file in webrootfor testing. Run from command
CD temp
Javac-D. src/ex01/pyrmont/*. Java
In this way, the ex01/pyrmont directory will appear in the current directory (D:/temp), which contains the compiled class file, and then runs
Java-duser. dir = D:/temp ex01.pyrmont. httpserver
Then input http: // localhost: 8080/index.html in the browser. In this case, you can see the static page index.html that serversends to you.

 

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.