A simple web server example and a simple web server example

Source: Internet
Author: User

A simple web server example and a simple web server example

A simple web Container example has simple functions and can only access static resources. It is of some significance for beginners. There are three main types:

1. server: The main function is to enable socketServer, block server, receive socket access, parse request, create request, and respond.

Public class TestServer1 {private boolean shutdown = false; // web directory webroot public static final String WEB_ROOT = System. getProperty ("user. dir ") + File. separator + "WebRoot"; public static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; public static void main (String [] args) {TestServer1 server = new TestServer1 (); server. await ();} public void await () {// Step 1: Create a serverSocket to listen to port 8080 of the local machine. Server = null; int port = 8080; try {server = new ServerSocket (port, 1, InetAddress. getByName ("127.0.0.1");} catch (Exception e) {e. printStackTrace ();} // Step 2: polling blocks socketServer while (! Shutdown) {Socket socket = null; InputStream input = null; OutputStream output = null; try {socket = server. accept (); input = socket. getInputStream (); output = socket. getOutputStream (); // Step 3: Create a request and parse the request Request req = new Request (input); req. parseRequest (); // Step 4: Create response Response response = new Response (output); response. setRequest (req); // Step 5: Send simple static resources and close the socket to end the session response. sendStaticRes (); socket. close (); // close command shutdown = req. getUri (). equals (SHUTDOWN_COMMAND);} catch (IOException e) {e. printStackTrace ();}}}}

Of course, the above is the simplest implementation, and it cannot implement multithreading. In fact, the web Container will certainly create a thread pool to receive requests.

 

2. The request mainly parses the input stream and encapsulates it into a request

Class Request {private InputStream input; private String uri; public Request (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 * Connection: Keep-Alive
* Cookie: if there is a cookie in this place, if there is a session and jsessionId */public void parseRequest (){
// Why do I get only 2048 characters? This is because the length of the request content is restricted by browser and server for security or other reasons. StringBuffer buffer = new StringBuffer (2048); byte [] bytes = new byte [2048]; int I; try {I = input. read (bytes);} catch (IOException e) {e. printStackTrace (); I =-1 ;}for (int k = 0; k <I; k ++) {buffer. append (char) bytes [k]);} System. out. println (buffer. toString (); uri = parseUri (buffer. toString ();}/*** GET/index.html HTTP/1.1 uri location * @ param reqStr * @ return */private String parseUri (String ReqStr) {int index1, index2; index1 = reqStr. indexOf (''); if (index1! =-1) {index2 = reqStr. indexOf ('', index1 + 1); if (index2> index1) return reqStr. substring (index1 + 1, index2);} return null;} public String getUri () {return uri ;}}

The specific content of the parsed http request. As a web developer, you should be familiar with the meaning of each field. This request is a request encapsulated by the browser according to the http protocol, it is certainly better to write this request by hand.

 

3. response finds the corresponding resource through the request uri to respond to the request. In actual situations, there must be static and dynamic resources such as servlet \ filter, but here we just do a simple static process.

Class Response {private OutputStream output; private Request request; public Response (OutputStream output) {this. output = output;} public void setRequest (Request req) {this. request = req;}/*** simple processing of static Resources * @ throws IOException */public void sendStaticRes () throws IOException {FileInputStream FS = null; try {File staticFile = new File (TestServer1.WEB _ ROOT, request. getUri (); if (staticFile. exists () {FD = new FileInputStream (staticFile); int I = 0; byte [] buf = new byte [1024];
// Stream copy I = Fi. read (buf, 0, 1024); while (I! =-1) {output. write (buf, 0, I); I = Fi. read (buf, 0, 1024 );}} else {// file not found 404 String errorMessage = "HTTP/1.1 404 File Not Found \ r \ n" + "Content-Type: text/html \ r \ n "+" Content-Length: 23 \ r \ n "+" \ r \ n "+"

What components should you be familiar with in the same response content?

HTTP/1.1 200 OK // response line Date: Sat, 31 Dec 2005 23:59:59 GMTContent-Type: text/html; charset = ISO-8859-1Content-Length: 122 

Now, a simple web container is ready to access static resources under the webRoot directory.

It can be accessed through a browser or through telnet. Telnet localhost 8080 In the cmd command line to connect to socketServer, and then wait for the input. Naturally, we enter the corresponding request message and press enter to return the response.

The above original articles from the old Luo House tree blog address: http://www.cnblogs.com/TimBing/

Related Article

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.