Simple Web server implementation

Source: Internet
Author: User

Preface on its own implementation of a simple Web server, because it is a simple Web server, so there is no particularly advanced technical content.

1. TCP Communication (SOCKET)

2. IO stream

3. Thread Pooling Technology

The server architecture is also simple:


The request class primarily implements the ability to parse URLs to get the path to the HTML file.

The response class implements reading HTML files and outputting HTML file content to the browser.

The server class consolidates the request class and the response class to implement the thread's Run method.

The test class implements the thread pool and is also the service startup class.

Is the content that the browser sends to the server:


Here are the following:

1. Log of server output


Page:


Here are some key codes:

Package Request;import Java.io.bufferedreader;import Java.io.ioexception;public class Request {private String Fileroute=null;private BufferedReader br=null;public Request (BufferedReader br) {THIS.BR=BR;} public void Parse () {String info=null; StringBuffer msg=new StringBuffer (); try {while ((Info=br.readline ())!=null && info.length () >0) {// Loop read the client's information msg.append (info);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Fileroute=parsefileroute (Msg.tostring ());}        Read the file path from the browser to the server's content rules private string Parsefileroute (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; }//gets the HTML file name public String Getfileroute () {return fileroute;}}

Package Response;import Java.io.bufferedreader;import Java.io.file;import java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.printwriter;public class Response {private PrintWriter pw=null;private string fileroute=null;public Response (PrintWriter pw, string fileroute) {THIS.PW=PW; This.fileroute=fileroute;} public void Doresponse () {File File=new file ("WebApp" +fileroute);//system.out.println (File.getabsolutepath ()); File.exists () | | !file.isfile ())//is not a file or does not exist return; FileInputStream Is=null;inputstreamreader Isr=null; BufferedReader br=null;try {is=new fileinputstream (file); Isr=new InputStreamReader (IS); Br=new BufferedReader (ISR); String info; StringBuffer msg=new StringBuffer (); while ((Info=br.readline ())!=null && info.length () >0) {// Iterate through HTML file contents msg.append (info);} Output the contents of the file to the browser pw.write (msg.tostring ());p W.flush ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally{//Close Resource try {if (br!=null) Br.close ( ); IF (isr!=null) isr.close (); if (is!=null) Is.close ();} catch (IOException e) {e.printstacktrace ();}}}}

Package Server;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.inputstream;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.printwriter;import java.net.InetAddress; Import Java.net.socket;import request. Request;import Response. response;/* * Socket communication based on TCP protocol, implementation of user login * Server-side */public Class Server implements Runnable {private Socket Socket=null;public Server (socket socket) {This.socket=socket;} @Overridepublic void Run () {System.out.println (Thread.CurrentThread (). GetName ());//output current thread name InputStream is=null;i Nputstreamreader Isr=null; BufferedReader Br=null;outputstream Os=null; PrintWriter PW=NULL;//1. Create a server-side socket, that is, ServerSocket, specify the bound port, and listen for this port try {//Receive request into blocking state inetaddress address= Socket.getinetaddress (); System.out.println ("IP of Current client:" +address.gethostaddress ()); SYSTEM.OUT.PRINTLN ("Current client port:" + socket.getport ()); Is=socket.getinputstream (); Isr=new InputStreamReader (IS); br=new BufferedReader (ISR); Request Request = new request (BR); Request.parse (); OS =Socket.getoutputstream ();p w = new PrintWriter (OS); Response Response = new Response (PW, Request.getfileroute ()); Response.doresponse ();} catch (IOException e) {//Todo:handle exceptione.printstacktrace ();} finally {//close resource try {if (pw!=null) pw.close (); if (os! =null) Os.close (); if (br!=null) br.close (); if (isr!=null) isr.close (); if (is!=null) is.close (); if (socket!=null) Socket.close ();} catch (IOException e) {e.printstacktrace ();}}}}

Package Test;import Java.io.ioexception;import Java.net.serversocket;import java.net.socket;import Java.util.concurrent.executorservice;import java.util.concurrent.executors;import Server. Server;public class Test {public static void main (string[] args) {Executorservice pool=null; ServerSocket serversocket=null;try {serversocket=new serversocket (80);//The number of thread pool threads that create a reusable fixed number of threads is 5    pool = Executors.newfixedthreadpool (5); Socket Socket=null;while (True) {socket=serversocket.accept ();//new Thread (New Server (socket)). Start ();p Ool.execute (New Server (socket));}} catch (IOException e) {e.printstacktrace ();} finally {if (pool!=null) Pool.shutdown (); try {if (serversocket!=null) Serversocket.close ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

A good practiced hand project, involving Java Io,socket, multi-threading, everyone can try to achieve.



Simple 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.