Java implements a simple web Server (Analysis + Source Code)

Source: Internet
Author: User
Tags sendfile

In daily development, we have used many open-source web servers, such as tomcat and apache. Now we implement a simple web server. The basic function is to click the resource to be accessed, and the server sends the resource to the browser of the client. To simplify the operation, exceptions such as resource does not exist are not considered here. The web Service is based on the HTTP protocol. When you enter the address to be accessed in the address bar of your browser, it is critical for the server to obtain the address. Let's take a look at the common formats of HTTP request and response packets:

HTTP Request Message

HTTP Response Message


When the web server obtains a user's connection, a thread is initialized to communicate with the user. The Code is as follows:

Import java. io. dataInputStream; import java. io. file; import java. io. fileInputStream; import java. io. IOException; import java. io. printStream; import java.net. socket; // when each connection is established, the server separates the public class CommunicateThread extends Thread {// Socket client that communicates with the client; public CommunicateThread (Socket s) {client = s;} // obtain the path of the resource requested by the browser public String getResourcePath (String s) {// the first line of a general HTTP request message is "GET/index.html HTTP/1.1" // what we want to obtain is the "/indext. apsx "// obtain the resource location String s1 = s. substring (s. indexOf ('') + 1); s1 = s1.substring (1, s1.indexOf (''); // The ingress resource is index.html if (s1.equals ("") s1 = "index.html "; return s1;} public void sendFile (PrintStream out, File file) {try {DataInputStream in = new DataInputStream (new FileInputStream (file); int len = (int) file. length (); byte buf [] = new byte [len]; in. readFully (buf); // read the text into the buf array out. write (buf, 0, len); out. flush (); in. close ();} catch (Exception e) {System. out. println (e. getMessage (); System. exit (1) ;}} public void run () {try {// obtain the user's IP address and port number String clientIP = client. getInetAddress (). toString (); int clientPort = client. getPort (); // create the output stream object PrintStream out = new PrintStream (client. getOutputStream (); // create the input stream object DataInputStream in = new DataInputStream (client. getInputStream (); // read the request String msg = in. readLine (); // get the file path String fileName = getResourcePath (msg); System. out. println ("The user asked for resource:" + fileName); File file = new File (fileName); if (file. exists () {// set System Based on the Response Message format. out. println (fileName + "start send"); out. println ("HTTP/1.0 200 OK"); out. println ("mime_versions: 1.0"); out. println ("Content_Type: text/html"); int len = (int) file. length (); out. println ("Content_Length:" + len); out. println (""); // a blank line is required between the packet header and the information. // The sendFile (out, file); out. flush ();} client. close ();} catch (Exception e) {System. out. println (e. getMessage ());}}}

The server is mainly responsible for initializing sockets and threads. The Code is as follows:

Import java.net. serverSocket; import java.net. socket; public class WebServer {public static void main (String [] args) {int Port = 12345; // Port number, because this is a test, therefore, do not use common ports // create two sockets ServerSocket server = null; Socket client = null; try {server = new ServerSocket (Port); // The server starts to listen to System. out. println ("The WebServer is listening on port" + server. getLocalPort (); while (true) {client = server. accept (); // run new CommunicateThread (client) in multiple threads ). start () ;}} catch (Exception e) {System. out. println (e. getMessage ());}}}


Run the test:

Compile an index.html File

This is the index of my WebServer
Put it in the root directory of the project file, and enter "localhost: 12345/index.html" in the address bar of the browser to view the html file on the server. Note: because the server is an endless loop, restart the server and you will find that the specified port has been bound. You only need to go to the task manager and close the "Java (TM) Platfrom SE binary" process. The final result is as follows:


This server program is very simple and there is still much room for improvement. You can try to improve it on your own. Here, you can try to access other files and find the files are successful, which means the server is not safe.



Related Article

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.