Java implements a simple HTTP Server

Source: Internet
Author: User

Use Java to implement simple HTTP servers

It is not difficult to implement, but you also need to fully master the basic Java programming. You also need to understand the HTTP protocol and the basic working principles of the HTTP server/client.

HTTP is a stateless protocol based on the request/response mode. Client (browser) and server (Web server application)Program) After the connection is established

For a request, the server processes the request, returns a response, and closes the connection between the two parties.

Here, we want to implement the process of responding to the "get" command after we get the "Browser" request. Let's take a look at the format of the "get" command in http:
GET request-Uri HTTP/1.1 // note that there must be no less space in the command line
When we access a webpage by entering the URL in the address bar of the browser, the browser uses the get method to request resources from the server.

Below isCode:

Httpserver class, that is, the class where the main () method of the startup server is located:

Import java. Io .*;
Import java.net. serversocket;
Import java.net. Socket;
Import java. util. properties;

Public class httpserver {

Public static void main (string [] ARGs ){

Try {
// To facilitate the versatility of the program, we define the properties attribute file to configure the directory of the Web Server
Properties pro = new properties ();
File F = new file ("D: \ properties.txt"); // put the property configuration file on disk D and Directory
Inputstream ins = new fileinputstream (f );
Serversocket Ss = new serversocket (80); // listen to port 80
Pro. Load (INS); // read the attribute File

String pH = pro. getproperty ("path"); // obtain the path property value.
System. Out. println (ph );
// Loop listening. When a client socket is obtained, the session thread is established and started.
While (true)
{
Socket Sk = ss. Accept ();
Session Se = new session (SK, pH );
Thread thread = new thread (SE );
Thread. Start ();
}
} Catch (ioexception e ){

E. printstacktrace ();
}
}
}

 

The session class inherits the runnable interface, which is convenient for the server to support multiple users (multithreading) and the GET command processing and response in the run () method:

Import java. Io .*;
Import java.net. Socket;
Import java. util .*;

public class session implements runnable {
private socket SK;
private string path;
Public static final int max_lenght = 1024;
// constructor, and the following directory of the socket and web files passed in
public session (socket SK, string path) {
This. SK = Sk;
This. path = path;
}

Public void run (){

Try {
Bufferedreader BR =
New bufferedreader (New inputstreamreader (SK. getinputstream ()));
Outputstream out = Sk. getoutputstream ();
// BR encapsulates the input stream of the server to read the request line s sent from the client.
String S = Br. Readline ();
While (s! = NULL ){
System. Out. println ("client command:" + S );
If (S. Length () <3) break;
// Obtain the "get" command
String cmd = S. substring (0, 3 );
If (CMD. cmdsignorecase ("get ")){
// Obtain the file name.
String filename = S. substring (5, S. lastindexof (""));
// Filepath is the absolute path of the file.
String filepath = path + filename;
System. Out. println (filepath );
// Read the file to the Buf Array
File file = new file (filepath );
If (! File. exists ()){
Filename = "index.html ";
File = new file (path + filename );
}
Inputstream in = new fileinputstream (File );
Byte [] Buf = new byte [max_lenght];
// Write the file to the client
Int n = 0;
While (n = in. Read (BUF ))! =-1 ){
Out. Write (BUF, 0, N );
Out. Flush ();

}
In. Close ();

}
S = Br. Readline ();

}
Out. Close ();
SK. Close ();

} Catch (ioexception e ){
E. printstacktrace ();
}

}

}

Download the source code. If you want to test the source code, you must create an attribute configuration file named “properties.txt in drive D and directory, and write a key-Value Pair in it: path = Your Local Web site and directory. Then compile --> Run. Open IE and enter http: // localhost: 80/index.html in the address bar (the port can be configured arbitrarily, but it must be consistent with the port listened by serversocket ).

Change the downloaded .txt suffix to .rar for decompression (no way, rar not supported)

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.