How Tomcat works reading notes (i)----------a simple Web server

Source: Internet
Author: User


HTTP protocol If two people can communicate normally, then they must have a unified language rules < server and client can communicate and rely on a set of rules, it is what we say HTTP rules (Hypertext Transfer Protocol Hypertext Transfer Protocol )。
HTTP is divided into two parts, one is the request (the client to the server), and the other is the reply (the server is sent to the client).
Look at the HTTP request first

Here is an example of an HTTP request, including the parameters, please refer to the relevant information. (http://www.cnblogs.com/yin-jingyu/archive/2011/08/01/2123548.html)



HTTP reply

Here is an example of HTTP reply, in addition to this diagram, the next part is the source of the page you see


Socket we generally say that the socket, broadly speaking, contains the socket class and the Serversocekt class under the java.net package.
On the other hand there are TCP-based network programming also has UDP-based network programming, which differs from everyone Baidu, here only talk about TCP.
The definition of things you can view a variety of information (personal recommendation still school horse soldier Teacher explained the socket part of the video, but before looking at the socket to see the IO part), take everyone to see a piece of code, we should know the general principle of socket programming. (Code from Horse Soldier Teacher's handout)


Import Java.net.*;import java.io.*;p ublic class TCPServer {public static void main (string[] args) throws Exception {Server      Socket ss = new ServerSocket (6666);                Listen while (true) {Socket s = ss.accept () on the TCP6666 port on this machine; ServerSocket's accept is a blocking method, only if it hears a request//it executes SYSTEM.OUT.P RINTLN ("A client connect!");D Atainputstream dis = new DataInputStream (S.getinputstream ());//Get the client to say to himself//input     Stream from outside points to memory System.out.println (Dis.readutf ()); Read content in uft-8 format dis.close (); S.close ();}}  Import Java.net.*;import java.io.*;p ublic class TCPClient {public static void main (string[] args) throws Exception {Socket       s = new Socket ("127.0.0.1", 6666);          Connect the 127.0.0.1 (native) TCP port 6666OutputStream OS = S.getoutputstream ();                             Get a line to "talk" to the server DataOutputStream dos = new DataOutputStream (OS);//Package The line Thread.Sleep (3000); "Pause" 3 seconds dos.writeutf ("Hello server!"); Say hello server! to the server Dos.flush ();d os.close (); S.close ();}}


Run the server side first and then the client side. When the client side is run, the console first prints a client connect! three seconds after the Hello server!
Simulate one of the most basic tomcat
Import Java.net.socket;import java.net.serversocket;import Java.net.inetaddress;import Java.io.InputStream;import Java.io.outputstream;import Java.io.ioexception;import Java.io.file;public class Httpserver {/** WEB_ROOT is the direct   Ory where our HTML and other files reside.   Web_root is the "Webroot" directory under the working * directory.   * The working directory is the location of the file system * from where the Java command was invoked.  */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 () {ServerSocket serversocket = null;    int port = 8080; try {serversocket = new ServerSocket (port, 1, Inetaddress.getbynamE ("127.0.0.1"));      This 1 is what the function participates in http://www.51cto.com/art/200702/40196_1.htm} catch (IOException e) {e.printstacktrace ();    System.exit (1);      }//Loop waiting for a request while (!shutdown) {///At the beginning of the shutdown to false this paragraph will execute socket socket = NULL;      InputStream input = null;      OutputStream output = null;   try {socket = serversocket.accept ();        It will only run the blocking method if there is a client request!  input = Socket.getinputstream ();         What's inside is what the client says to the server output = Socket.getoutputstream ();//This is what the server is going to say to the client//Create Request object and parse        Request Request = new request (input);                  Request.parse ();        See 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 }    }  }}




Import Java.io.inputstream;import Java.io.ioexception;public class Request {private 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 = new StringBuffer (2048);    int i;    byte[] buffer = new byte[2048];              try {i = input.read (buffer);      } catch (IOException e) {e.printstacktrace ();    i =-1;   } for (int j=0; j<i; J + +) {request.append ((char) buffer[j]);    Add client requests to request (StringBuffer)} System.out.print (Request.tostring ());     URI = Parseuri (request.tostring ());  System.out.print (uri****); }/** * See System.out.print (uri****);    You don't have to explain this method. * * **/private string Parseuri (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;  } public String GetURI () {return URI; }}




Import java.io.outputstream;import java.io.ioexception;import java.io.fileinputstream;import java.io.File;/* HTTP Response = Status-line * ((general-header | response-header | entity-header) CRLF) CRLF [Message-body] Stat  Us-line = http-version sp Status-code sp reason-phrase Crlf*/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 {System.out.println (httpserver.web_root+ "ss" +request.geturi ());   File File = new file (Httpserver.web_root, Request.geturi ());        Connect user Requested "file" if (File.exists ()) {FIS = new FileInputStream (file);       int ch = fis.read (bytes, 0, buffer_size); Read what's in the file and put it in the bytes character array while (cH!=-1) {//Put the contents of the bytes array inside the stream to be replied to the client output.write (bytes, 0, ch);        ch = fis.read (bytes, 0, buffer_size); }} else {//If file does not exist not explained//File not found String Erro Rmessage = "http/1.1 404 File Not found\r\n" + "content-type:text/html\r\n" + "content-length:23\r\n" + "\ r \ n" + "

First of all, if you are using eclipse, then there is no problem, if you are in the form of command line, there will be a problem, httpserver and response two classes interdependent, first compiled who?
Workaround CD to a directory of three classes and then Javac *.java


After starting the Httpserver,
In the browser input localhost:8080/index.html

Shown below



See, we put index.html in D:\ Academy J2ee\javase\ Academy Technology _ Horse Soldier _j2se_5.0_ No. 01 Chapter _java Introduction _ Source Code _ and important Description \java\socket\no\webcontent directory



Index.html content is as follows
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>insert title here</title>
<body>
I am index
</body>

Request again as follows




Everybody must be very strange, why I don't use Firefox or this chrome, find a editplus point to come over.
People try to know, Firefox does not know for what reason, in the address bar after hitting enter, will make two requests. The result is an error.


Try Http://localhost:8080/SHUTDOWN again.


Program exit


How Tomcat works reading notes (i)----------a simple 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.