A simple Java Web server implementation

Source: Internet
Author: User

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

Program execution steps
  1. Create a ServerSocket object;
  2. Call the Accept method of the ServerSocket object, wait for the connection, the successful connection will return a socket object, otherwise blocking the wait;
  3. Gets the InputStream and outputstream byte streams from the socket object that correspond to request requests and response responses respectively;
  4. processing request: Reading inputstream byte stream information, turn into a string form, and parse, here the resolution is relatively simple, just get Uri ) information;
  5. Processing response: Based on the parsed URI information, look for the requested resource resource file from the Web_root directory, read the resource file, and write it to the outputstream byte stream ;
  6. Close the socket object;
  7. Go to step 2 and continue waiting for the connection request;
Code implementation

Server implementation:

 PackageEx01.pyrmont;ImportJava.net.Socket;ImportJava.net.ServerSocket;Importjava.net.InetAddress;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.io.IOException;ImportJava.io.File; Public classHttpserver {/*** Web_root is the directory where HTML and other files are stored. Web_root here is the Webroot directory under the working directory*/     Public Static FinalString web_root = System.getproperty ("User.dir") + File.separator + "Webroot"; //Close Service Command    Private Static FinalString Shutdown_command = "/shutdown";  Public Static voidMain (string[] args) {httpserver server=NewHttpserver (); //Wait for connection requestserver.await (); }     Public voidawait () {ServerSocket ServerSocket=NULL; intPort = 8080; Try {            //Server Socket ObjectServerSocket =NewServerSocket (port, 1, Inetaddress.getbyname ("127.0.0.1")); } Catch(IOException e) {e.printstacktrace (); System.exit (1); }        //Loop waits for a request         while(true) {Socket Socket=NULL; InputStream input=NULL; OutputStream Output=NULL; Try {                //wait for connection, after successful connection, return a socket objectSocket =serversocket.accept (); Input=Socket.getinputstream (); Output=Socket.getoutputstream (); //create a Request object and parseRequest Request =NewRequest (input);                Request.parse (); //Check whether the service command is closed                if(Request.geturi (). Equals (Shutdown_command)) { Break; }                //Create a Response objectResponse Response =NewResponse (output);                Response.setrequest (Request);                Response.sendstaticresource (); //close the Socket objectSocket.close (); } Catch(Exception e) {e.printstacktrace (); Continue; }        }    }}

Request class:

 PackageEx01.pyrmont;ImportJava.io.InputStream;Importjava.io.IOException; Public classRequest {PrivateInputStream input; PrivateString URI;  PublicRequest (InputStream input) { This. Input =input; }    //read the request information from the InputStream and get the URI value from the request     Public voidParse () {StringBuffer request=NewStringBuffer (2048); inti; byte[] buffer =New byte[2048]; Try{i=input.read (buffer); } Catch(IOException e) {e.printstacktrace (); I=-1; }         for(intj = 0; J < I; J + +) {request.append (Char) buffer[j]);        } System.out.print (Request.tostring ()); URI=Parseuri (request.tostring ()); }    /*** * requeststring form as follows: * get/index.html http/1.1 * host:localhost:8080 * Connection:keep-aliv E * cache-control:max-age=0 * ... * This function is intended to get the/index.html string*/    Privatestring Parseuri (String requeststring) {intindex1, Index2; Index1= Requeststring.indexof (' '); if(Index1! =-1) {Index2= Requeststring.indexof (", Index1 + 1); if(Index2 >index1)returnRequeststring.substring (index1 + 1, INDEX2); }        return NULL; }     PublicString GetURI () {returnURI; }}

Response class:

 PackageEx01.pyrmont;ImportJava.io.OutputStream;Importjava.io.IOException;ImportJava.io.FileInputStream;ImportJava.io.File;/*HTTP Response = Status-line * ((general-header | response-header | entity-header) CRLF) CRLF [Message-bod Y] status-line = http-version sp status-code sp reason-phrase CRLF*/ Public classResponse {Private Static Final intBuffer_size = 1024;    Request request;    OutputStream output;  PublicResponse (OutputStream output) { This. Output =output; }     Public voidsetrequest (Request request) { This. Request =request; }     Public voidSendstaticresource ()throwsIOException {byte[] bytes =New byte[Buffer_size]; FileInputStream FIS=NULL; Try {            //writes a web file to the OutputStream byte streamFile File =NewFile (Httpserver.web_root, Request.geturi ()); if(File.exists ()) {FIS=Newfileinputstream (file); intch = fis.read (Bytes, 0, buffer_size);  while(ch! =-1) {output.write (bytes,0, CH); CH= Fis.read (Bytes, 0, buffer_size); }            } Else {                //File not foundString errormessage = "http/1.1 404 File Not found\r\n" + "content-type:text/html\r\n" + "content- length:23\r\n "+" \ r \ n "+" ;            Output.write (Errormessage.getbytes ()); }        } Catch(Exception e) {//thrown if cannot instantiate a File objectSystem.out.println (e.tostring ()); } finally {            if(FIS! =NULL) Fis.close (); }    }}
Results test

Access the existing resource files (note the Webroot folder in the project directory):

To access a resource file that does not exist:

To shut down the server:

Reference: Deep analysis of Tomcat

A simple Java Web server implementation

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.