A simple example of a Web server

Source: Internet
Author: User

A simple web container small example, the function is very simple, only access to static resources, for the novice still has a certain meaning. Three main categories

1. Server class: Main function Open Socketserver, block server, receive socket access, parse request, create request, respond

 Public classTestServer1 {Private Booleanshutdown =false; //Web Directory Webroot     Public Static FinalString web_root = System.getproperty ("User.dir")             + File.separator + "WebRoot";  Public Static FinalString Shutdown_command = "/shutdown";  Public Static voidMain (string[] args) {TestServer1 server=NewTestServer1 ();    Server.await (); }         Public voidawait () {//The first step, create the ServerSocket monitor native 8080 PortServerSocket Server =NULL; intPort = 8080; Try{Server=NewServerSocket (port, 1, Inetaddress.getbyname ("127.0.0.1")); } Catch(Exception e) {e.printstacktrace (); }                 //The second step, polling blocking live Socketserver         while(!shutdown) {Socket Socket=NULL; InputStream input=NULL; OutputStream Output=NULL; Try{Socket=server.accept (); Input=Socket.getinputstream (); Output=Socket.getoutputstream (); //step three, create a request, and parse requestsRequest req =NewRequest (input);                                Req.parserequest (); //Fourth Step, create responseResponse Response =NewResponse (output);                                Response.setrequest (req); //Fifth Step, send a simple static resource, close the socket to end this sessionresponse.sendstaticres ();                                Socket.close (); //Close Commandshutdown =Req.geturi (). Equals (Shutdown_command); } Catch(IOException e) {e.printstacktrace (); }        }            }    }

Of course, above is the simplest implementation, and can not implement multi-threading, the actual Web container will definitely create a thread pool to receive requests

2, request the main work parse input stream, encapsulated into request

classRequest {PrivateInputStream input; PrivateString URI;  PublicRequest (InputStream input) { This. Input =input; }            /*** Parse Request content * get/index.html http/1.1 * accept:text/html, Application/xhtml+xml,*//** ACCEPT-LANGUAGE:ZH-CN * user-agent:mozilla/5.0 (Windows NT 6.3; WOW64; trident/7.0; Malcjs; rv:11.0) Like Gecko * accept-encoding:gzip, deflate * host:localhost:8080 * dnt:1 * Connect Ion:keep-alive
* Cookie: This place should have a cookie if there is a session and Jsessionid*/ Public voidParserequest () {
Why only 2048 characters are obtained, this is because the request requests the length of the content, for security or other considerations, the browser side and the server side will make such a limit. StringBuffer Buffer=NewStringBuffer (2048); byte[] bytes =New byte[2048]; inti; Try{i=input.read (bytes); } Catch(IOException e) {e.printstacktrace (); I=-1; } for(intI=r; k<i; k++) {buffer.append (Char) bytes[k]); } System.out.println (Buffer.tostring ()); URI=Parseuri (buffer.tostring ()); } /*** get/index.html The location of the http/1.1 URI *@paramReqstr *@return */ Privatestring Parseuri (String reqstr) {intindex1, Index2; Index1= Reqstr.indexof (' '); if(Index1! =-1) {Index2= Reqstr.indexof (", Index1 + 1); if(Index2 >index1)returnReqstr.substring (index1 + 1, INDEX2); } return NULL; } PublicString GetURI () {returnURI; } }

Parsing the specifics of the HTTP request, as Web developers should be familiar with the meaning of each field, this request is the browser itself in accordance with the HTTP protocol encapsulated a request, it is certainly better to write this request.

3, response through the request URI to find the corresponding resources to respond to requests, the actual situation must be static and dynamic resources such as servlet\filter and so on, but here just do a simple static processing

classResponse {Privateoutputstream output; PrivateRequest request;  PublicResponse (OutputStream output) { This. Output =output; }         Public voidsetrequest (Request req) { This. Request =req; }        /*** Simple handling of static resources *@throwsIOException*/     Public voidSendstaticres ()throwsIOException {fileinputstream fis=NULL; Try{File Staticfile=NewFile (Testserver1.web_root, Request.geturi ()); if(Staticfile.exists ()) {FIS=NewFileInputStream (Staticfile); inti = 0; byte[] buf =New byte[1024];
The copy of the stream I= Fis.read (buf, 0, 1024); while(I!=-1) {output.write (buf,0, i); I= Fis.read (buf, 0, 1024); } } Else { //file not found 404String 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) {e.printstacktrace (); } finally{ if(fis!=NULL) Fis.close (); FIS=NULL; } }}

Same response content you should also be familiar with which components

http/1.1 OK // response line Date:sat, 2005 23:59:59 gmtcontent-type:text/html;charset=iso-8 859-1 Content-length:122    test  This my page</body>

At this point a simple Web container is written to access the static resources under the Webroot directory.

It can be accessed through the browser or via the Telnet side. In the cmd command line telnet localhost 8080, will be connected to the Socketserver, and then will wait for input, naturally we enter the corresponding request message, enter the response content appears.

The original article from the Old Luo family tree blog address: http://www.cnblogs.com/TimBing/

A simple example of a Web server

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.