Tomcat Learning Notes (i) a simple Web server

Source: Internet
Author: User

the content is "deep analysis of Tomcat," the first chapter of the focus, as well as their own summary, if the description is unclear, you can view the original book. First, HTTP protocol:1, definition: The protocol used for communication between server and client, allowing Web servers and browsers to send and receive data over the Internet. is a request and response protocol that uses a reliable TCP protocol with a TCP protocol port of 80, which is a connection-oriented protocol. 2, the HTTP protocol request three components: the three parts with carriage return newline character (CRLF) separates the request part: The method (Get/post and so on 7 kinds, other seldom uses, the book has introduced) [the space, this part content is separated by the space] Uniform Resource Identifier uri[space, the part content is separated by the space     The Protocol/Protocol version URL is usually the root of the relative server, and therefore begins with "/". Request Header: The header of the request contains useful information about the client environment and the principal content of the request. For example, it may include the language of the browser settings, the length of the body content, and so on.     Each header is delimited by a carriage return newline character (CRLF). Request Principal content: For HTTP request format, it is important to have a carriage return (CRLF) between the header and the body content. Crlf tells the HTTP server where the principal content started. In some Internet programming books, CRLF is also considered the fourth part of the HTTP request. 3, the HTTP response also includes three parts: · Method-Uniform Resource Identifier (URI)-Protocol/version · The head of the response• Main content Two, server and client communication 1, the server and client communication needs to use two parts: socket (client) and ServerSocket (server side) (1) serversocket (java.net.ServerSocket, server-side sockets), to create a server socket, You need to use one of the four constructor methods provided by the ServerSocket class. You need to specify the IP address and port number that the server socket will listen on. Typically, the IP address will be 127.0.0.1, which means that the server socket will listen to the local machine. The IP address that the server socket is listening on is called a binding address. Another important property of the server socket is the backlog, which is the maximum queue length for incoming connection requests before the server socket starts rejecting incoming requests, and four construction methods are:          ServerSocket ss = new ServerSocket ();//Create an unbound serversocket          serversocket ss = new S Erversocket (int port);//Create a serversocket  bound to a port         serversocket SS = new ServerSocket (int port, int log);//Create a ServerSocket bound to a port and set the maximum queue length.           ServerSocket ss = new ServerSocket (int port, int log, inetaddress address);//Create a binding to an address , ServerSocket for a port, and sets the maximum queue length.           for the fourth construction method, the binding address must be an instance of InetAddress, and a simple way to construct a InetAddress object is to call its static method Getbyname, Pass in a string containing the host name, just like the following code.                inetaddress. Getbyname ("127.0.0.1");      Common ways to create ServerSocket:                 New ServerSocket (8080, 1, inetaddress.getbyname ("127.0.0.1"));      The code constructs a servletsocket that listens on the local machine 8080 port, its queue length is 1.       server is created to wait state (TCP protocol, reliable transport Protocol, is the synchronization protocol, (2) socket (Java.net.Socket class, client socket): You need to know the ip/hostname and port number of the server side you want to access, you can send requests to the server side. The socket               new socket ("yahoo.com") can be established using one of the many construction methods of the socket. ,;      Once you have successfully created an instance of a socket class, you can use it to send and receive byte streams. To send a byte stream, you first have to call the Getoutputstream method of the socket class to get a Java.io.OutputStream object. To send text to a remote application, you often construct a Java.io.PrintWriter object from the returned OutputStream object. To accept a byte stream from the other end of the connection, you can call the getInputStream method of the socket class to return a Java.io.InputStream object.   (3) The server side receives the client's connection request through the Accept () method and establishes a connection with the client, returning a socket          Socket s =  ss. Accept (); (4) an input stream and an output stream are obtained through the socket, and the input stream is used to read the client request data, and the output stream is used to return the response information to the client. For example: inputstream input =  s.geTinputstream ();          OutputStream output = S.getoutputstream (); three, simple Web server communication example (recommended copy to MyEclipse to see and execute)1. Server class
Package Com.socket.httpservertest;import Java.io.file;import Java.io.ioexception;import java.io.InputStream;import Java.io.outputstream;import Java.net.inetaddress;import Java.net.serversocket;import Java.net.Socket;public class     Httpserver {public static final String web_root = System.getproperty ("User.dir") + File.separator + "Webroot";     Shutdown command private static final String Shutdown_command = "/shutdown";     The shutdown command received private Boolean shutdown = false;           public static void Main (string[] args) {httpserver server = new Httpserver ();                Server.await ();           } public void await () {//System.out.println (System.getproperty ("User.dir"));           ServerSocket serversocket = null;           int port = 8080;           try {serversocket = new ServerSocket (port, 1, Inetaddress.getbyname ("127.0.0.1"));              } catch (IOException e) {e.printstacktrace ();  System.exit (1);                } while (!shutdown) {socket socket = NULL;                InputStream input = null;                OutputStream output = null;                     try {//received a request from the client, otherwise the consistency is the wait state socket = serversocket.accept ();                     input = Socket.getinputstream ();                     Output = Socket.getoutputstream ();                     Create request object and parse Request request = new request (input); Request.parse ();                     Read content from request//Create Response object Response Response = new Response (output);                     Response.setrequest (Request);                     Response.sendstaticresource ();                     Close the socket Socket.close (); Check if the previous URI is a shutdown command shutdown = Request.geturi (). Equals (Shutdown_command)     ;           }catch (Exception e) {e.printstacktrace ();                Continue }           }    }}
2. Request Class
Package Com.socket.httpservertest;import Java.io.ioexception;import Java.io.inputstream;public class Request {privat     e InputStream input;     Private String URI;     Public Request (InputStream input) {this.input = input; } public void Parse () {//Read a set of characters from the socket stringbuffer request = NE           W StringBuffer (2048);           int i;           byte[] buffer = new byte[2048]; try {i = input.read (buffer),//the contents of 2048 length from the input stream are stored in the buffer byte array, and if the content is less than 2048, the remaining space in the array is empty} catch (Ioexc                Eption e) {e.printstacktrace ();           i =-1;           } for (int j=0; j<i; J + +) {request.append ((char) buffer[j]);           } System.out.print (Request.tostring ());     URI = Parseuri (request.tostring ());           } private String Parseuri (string requeststring) {int index1, index2; Index1 = RequeststriNg.indexof (");            /* HTTP Request Line structure: Method Uniform Resource Identifier (URI) protocol/version (they are separated by a space) * For example: POST//examples/default.jsp http/1.1 */if (index1! =-1) {//Index1 = =-1 means not found Index2 = Requeststring.indexof (", index1 + 1)  ;//start looking for ' if ' (Index2 > Index1) return from index+1 position requeststring.substring (index1                + 1, INDEX2);     } return null;     } public String GetURI () {return URI; }}
3. Response Class
Package Com.socket.httpservertest;import Java.io.file;import Java.io.fileinputstream;import java.io.IOException;     Import Java.io.outputstream;public class Response {private static final int buffer_size = 1024;     Request request;     OutputStream output;     Public Response (OutputStream output) {this.output = output;     } public void Setrequest (Request request) {this.request = Request;           } public void Sendstaticresource () throws IOException {byte[] bytes = new Byte[buffer_size];           FileInputStream FIS = null;                try {File File = new file (Httpserver.web_root, Request.geturi ());                     if (file.exists ()) {FIS = new FileInputStream (file);                     int ch = fis.read (bytes, 0, buffer_size);                           while (ch!=-1) {//ch==-1 = read at the end of Output.write (bytes, 0, ch);//write to Browser ch = fis.read (bytes, 0, buffer_size);//Reading will be read at the last read, if read to the end will return-1, terminating output}} else {//File not found String errormessage = "http/1.1 404 File Not found\r\n" + "content-type:text/html\r\n" + "Content-length:2                     3\r\n "+" \ r \ n "+" 4. Sample code Function Description: Browser input HTTP request, such as http://localhost:8080/ myhtml.html; After the server receives the request, the input stream reads the request content to obtain the file location, then reads the contents of the file with the file input stream, and finally returns the response to the browser client, displaying the contents of the HTML file on the browser, 5, the sample code cross-Functional Flowchart:

Tomcat Learning Notes (i) a simple Web server

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.