A simple Java web server implementation, Java web Server

Source: Internet
Author: User

A simple Java web server implementation, Java web Server

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

Code Implementation of program execution steps

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:

 

References: in-depth analysis of Tomcat

 

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.