A simple Java Web server implementation

Source: Internet
Author: User

A simple Java Web server implementation

A simple Java web server implementation is relatively simple, based on java.net. Socket and java.net. ServerSocket;

Procedure
  1. Create a ServerSocket object;
  2. Call the accept method of the ServerSocket object and wait for the connection. If the connection is successful, a Socket object will be returned. Otherwise, the wait will be blocked;
  3. Obtain the InputStream and OutputStream byte streams from the Socket object. These two streams correspond to the request and response respectively;
  4. Request Processing: Read the InputStream byte stream information, convert it to the string format, and parse it. The parsing here is relatively simple. Only uri (unified resource identifier) information is obtained;
  5. Processing response: Find the requested resource file from the WEB_ROOT directory based on the parsed uri information, read the resource file, and write it into the OutputStream byte stream;
  6. Disable the Socket object;
  7. Go to step 2 and wait for the connection request;
Code Implementation

Server implementation:

Package ex01.pyrmont; import java.net. socket; import java.net. serverSocket; import java.net. inetAddress; import java. io. inputStream; import java. io. outputStream; import java. io. IOException; import java. io. file; public class HttpServer {/*** WEB_ROOT is the directory where HTML and other files are stored. here, WEB_ROOT is the webroot directory under the working directory */public static final String WEB_ROOT = System. getProperty ("user. dir ") + File. separator + "webroot"; // close the service command private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; public static void main (String [] args) {HttpServer server = new HttpServer (); // wait for the connection request to server. await ();} public void await () {ServerSocket serverSocket = null; int port = 8080; try {// server socket object serverSocket = new ServerSocket (port, 1, InetAddress. getByName ("127.0.0.1");} catch (IOException e) {e. printStackTrace (); System. exit (1);} // wait for a request in a loop while (true) {Socket socket = null; InputStream input = null; OutputStream output = null; try {// wait for the connection, after the connection is successful, a Socket object socket = serverSocket is returned. accept (); input = socket. getInputStream (); output = socket. getOutputStream (); // create a Request object and parse the Request request = new Request (input); request. parse (); // check whether the service command if (request. getUri (). equals (SHUTDOWN_COMMAND) {break;} // create the Response object Response response = new Response (output); response. setRequest (request); response. sendStaticResource (); // closes the socket object socket. close ();} catch (Exception e) {e. printStackTrace (); continue ;}}}}

Request class:

Package ex01.pyrmont; import java. io. inputStream; import java. io. IOException; public class Request {private InputStream input; private String uri; public Request (InputStream input) {this. input = input;} // read the request information from InputStream and obtain the uri value public void parse () {StringBuffer request = new StringBuffer (2048); int I; byte [] buffer = new byte [2048]; try {I = input. read (buffer);} catch (IOExcep Tion 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 ();}/*** requestString format: * GET/index.html HTTP/1.1 * Host: localhost: 8080 * Connection: keep-alive * Cache-Control: max-age = 0 *... * This function is used to obtain the/index.html String */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;} public String getUri () {return uri ;}}

Response class:

Package ex01.pyrmont; import java. io. outputStream; import java. io. IOException; import java. io. fileInputStream; import java. io. file;/* HTTP Response = Status-Line * (general-header | response-header | entity-header) CRLF) CRLF [message-body] Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF */public class Response {private static final int BUFFER_SIZE = 1024; Request request; OutputStr Eam output; public Response (OutputStream output) {this. output = output;} public void setRequest (Request request) {this. request = request;} public void sendStaticResource () throws IOException {byte [] bytes = new byte [BUFFER_SIZE]; FileInputStream FCM = null; try {// write the web File to the OutputStream byte stream file = new File (HttpServer. WEB_ROOT, request. getUri (); if (file. exists () {FS = new FileInputSt Ream (file); int ch = Fi. 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 "+" Result Test

Access the existing resource file (note that it is stored in the webroot folder of the project directory ):

Access a nonexistent resource file:

Disable the server:

 

Reference: in-depth analysis of Tomcat PDF download

This article permanently updates the link address:

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.