One of the simplest static Web servers

Source: Internet
Author: User

Disclaimer: The data comes from the Tomcat Anatomy book, which is based on the Java socket, socket and stream classes as a conceptual background, now just use it as the base class, not paying attention to itself, focus on the external features and architecture of a server!

    • Code Catalog

  

    • Httpserver
 PackageSimpleserver;ImportJava.io.File;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.InetAddress;ImportJava.net.ServerSocket;ImportJava.net.Socket;/*** Description: Server The service personally manages the request, and response, the current service is just a static resource service; * request is used to parse the requested data stream and abstract it into the requested object * response according to the request path to the root The directory looks for resources and outputs; The program responds with only the response body * * As a static server, the program needs to be perfected: the response object itself *@authorAdministrator **/ Public classHttpserver { Public Static FinalString web_root = System.getproperty ("User.dir") +file.separator+ "Webroot";//Specifies the static resource directory, the root directory of the request path        Private Static FinalString Shutdown_command = "/shutdown"; Private Booleanshutdown =false;  Public Static voidMain (String[]args) {System.out.println ("Print output Web_root" +web_root); Httpserver ServerSocket=NewHttpserver ();  Serversocket.await (); //service startup    }         Public voidawait () {ServerSocket ServerSocket=NULL; intPort = 8080; Try{ServerSocket=NewServerSocket (port, 1, Inetaddress.getbyname ("192.168.1.102"));//The port number of the binding service, the number of connections, the address to which the service is to be connected}Catch(IOException e) {e.printstacktrace (); System.exit (1); }         while(!shutdown) {Socket Socket=NULL; InputStream input=NULL; OutputStream Output=NULL; Try{Socket= Serversocket.accept ();//1 listening in here, blockinginput =Socket.getinputstream (); Output=Socket.getoutputstream (); Request Request=NewRequest (input);//2 The data is passed to the request for parsing; the input stream of the socket is requestedRequest.parse (); Response Response=NewResponse (output);//3 The Response object looks for resources based on the resolved request path and responds to the output stream using the socketresponse.setrequest (Request);                Response.sendstaticresource ();                                Socket.close (); //4 The socket is closed after the response is sent back, and the service is stillshutdown =Request.geturi (). Equals (Shutdown_command); }            Catch(Exception e) {e.printstacktrace (); Continue; }                    }            }}
View Code
    • Request
 PackageSimpleserver;Importjava.io.IOException;ImportJava.io.InputStream;/*** @ Description: The InputStream of the socket class is parsed to generate many properties, which are subordinate to the class *@authorAdministrator **/ Public classRequest {PrivateInputStream input; PrivateString URI;  PublicRequest (InputStream input) { This. Input =input; }     PublicString GetURI () {returnURI; }     Public voidParse () {StringBuffer request=NewStringBuffer (); 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.println (Request.tostring ()); URI=Parseuri (request.tostring ()); System.out.println ("Intercepted path" +URI); }    PrivateString Parseuri (String requeststring) {//resolves only the URI attribute in the request data        intindex1, Index2; Index1= Requeststring.indexof (' '); if(Index1! =-1) {Index2= Requeststring.indexof (", Index1 + 1); if(Index2 >index1) {                returnRequeststring.substring (index1+1, INDEX2); }        }        return NULL; }}
View Code
    • Response
 PackageSimpleserver;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.OutputStream; 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{File File=NewFile (Httpserver.web_root, Request.geturi ());//1 root directory stitching request pathSYSTEM.OUT.PRINTLN ("Request Path" +File.getabsolutepath ()); if(File.exists ()) {System.out.println ("File exists"); FIS=Newfileinputstream (file); intch = fis.read (Bytes, 0, buffer_size);  while(Ch!=-1) {output.write (bytes,0, CH);//2.1 Requested response data is written to the output streamch = fis.read (Bytes, 0, buffer_size); }            }            Else{String errormessage= "http/1.1 404 File Not Found\r\n"//2.2 response data written to the output stream+ "content-type:text/html\r\n" + "content-length:23\r\n" + "\ r \ n" + ";            Output.write (Errormessage.getbytes ()); }        }Catch(Exception e) {System.out.println (e.tostring ()); }finally {            if(fis!=NULL) {fis.close (); }        }            }        }
View Code

One of the simplest static Web servers

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.