Web Request Response principle (GO)

Source: Internet
Author: User
Tags sendfile

Implementing a Web server with Java

Decrease Font Increase Font

Absrtact: The work of WWW is based on the client/server computing model, which consists of a Web browser (client) and a Web server (server), which uses Hypertext Transfer Protocol (HTTP) to communicate, and the principle of the HTTP protocol consists of four steps: Connect, request, answer. According to the principle of the above HTTP protocol, this paper implements the method of Get Request Web server program, by creating the ServerSocket class object, listening on port 8080, waiting, accepting the client connection to port 8080, creating the input stream and output stream associated with the socket word; , read the client's request information, if the request type is get, get the HTML file name accessed from the request information, if the HTML files exist, open the HTML file, the HTTP header information and HTML file content through the socket back to the Web browser, and then close the file. Otherwise, send an error message to the Web browser. Finally, close the socket word that is connected to the corresponding Web browser.

I. How the HTTP protocol works

WWW is an application system with Internet as transmission medium, and the most basic transmission unit of WWW is Web page. The work of WWW is based on the client/server computing model, which consists of a Web browser (client) and a Web server (server) that communicate using Hypertext Transfer Protocol (HTTP). HTTP protocol is a protocol based on TCP/IP protocol, which is the application layer protocol between Web browser and Web server, and is a general, stateless, object-oriented protocol. The principle of the HTTP protocol consists of four steps:

(1) Connection: the Web browser establishes a connection to the Web server and opens a virtual file called a socket (socket), which establishes a successful connection establishment.

(2) Request: The Web browser submits a request to the Web server through a socket. HTTP requests are typically GET or post commands (the post is used for the pass of the form parameter). The format of the Get command is:

GET path/file name http/1.0

The file name indicates which files are accessed, and http/1.0 indicates the HTTP version used by the Web browser.

(3) Answer: After the Web browser submits the request, it is routed to the Web server via the HTTP protocol. After the Web server is received, the transaction is processed, and the results are passed back to the Web browser via HTTP to display the requested page on the Web browser.

Example: Suppose the client establishes a connection with www.mycompany.com:8080/mydir/index.html, it sends a GET command: get/mydir/index.html http/1.0. The Web server with the hostname www.mycompany.com searches its document space for the Mydir file index.html of the subdirectory. If the file is found, the Web server transmits the file content to the appropriate Web browser.

To tell the Web browser what type of content to transfer, the Web server first transmits some HTTP header information and then transmits the specific content (that is, the HTTP body information) separated by a blank line between the HTTP header information and the HTTP body information.

The commonly used HTTP header information is:

  ①http 1.0-OK

This is the first line of the Web server answer that lists the HTTP version number and the answer code that the server is running. The code "200OK" indicates that the request is complete.

②mime_version:1.0

It indicates the version of the MIME type.

③content_type: Type

This header information is very important and it indicates the MIME type of the HTTP body information. Such as: Content_type:text/html indicates that the transmitted data is an HTML document.

④content_length: Length Value

It indicates the length of the HTTP body information (in bytes).

(4) Close connection: When the answer is finished, the Web browser and Web server must be disconnected to ensure that other Web browsers can connect to the Web server.

Second, Java implementation of Web server function design

Based on the principle of the above HTTP protocol, the method of implementing a GET Request Web server program is as follows:

(1) Create the ServerSocket class object and listen on port 8080. This is to distinguish the HTTP from the standard TCP/IP port 80;

(2) Wait, accept the client connection to port 8080, get the socket connected to the client;

(3) Create the input stream instream and output stream outstream associated with the socket word;

(4) from the input stream instream associated with the socket, read the request information submitted by a row of clients, the format of the request information is: GET path/file name http/1.0

(5) Obtain the request type from the request information. If the request type is get, the access HTML file name is obtained from the request information. When there is no HTML file name, index.html is used as the file name;

(6) If the HTML file exists, open the HTML file, send the HTTP header information and HTML file content to the Web browser via the socket, and then close the file. Otherwise send error message to Web browser;

(7) Close the socket that is connected to the corresponding Web browser.

The following program is a multi-threaded Web server that is written according to the above method to ensure that multiple clients can connect to the Web server at the same time.

Program 1:webserver.java File

//Webserver.java writing a Web server in Javaimport java.io.*; Import java.net.*;  Public classWebServer { Public Static voidMain (stringargs[]) {intI=1, port=8080; ServerSocket Server=NULL; Socket Client=NULL; Try{Server=Newserversocket (PORT); System. out. println ("WebServer is listening on port"+Server.getlocalport ());  for (;;) {Client=server.accept ();//accepting connection requests from clientsNewconnectionthread (client,i). Start (); I++; }}Catch(Exception e) {System. out. println (e);} }    }        /*Connnectionthread class completes communication with a Web browser*/    classconnectionthread extendsthread {Socket client;//Connect to the Web browser's socket     intCounter//counter      PublicConnectionthread (SOCKETCL,intc) {client=cl; Counter=C; } Public voidRun ()//Thread Body{Try{Stringdestip=client.getinetaddress (). toString ();//Client IP AddressIntdestport=client.getport ();//Client Port numberSystem. out. println ("Connection"+counter+": Connected to"+destip+"On Port"+destport+"."); PrintStream OutStream=Newprintstream (Client.getoutputstream ()); DataInputStream instream=Newdatainputstream (Client.getinputstream ()); Stringinline=instream.readline ();//read request information submitted by web browserSystem. out. println ("Received:"+inline); if(Getrequest (inline)) {//if it is a GET requestStringfilename=GetFileName (inline); File File=newFile (filename); if(File.exists ()) {//If the file exists, send the file to the Web browserSystem. out. println (filename+"requested."); Outstream.println ("http/1.0200 OK"); Outstream.println ("mime_version:1.0"); Outstream.println ("content_type:text/html"); Intlen=(int) file.length (); Outstream.println ("content_length:"+Len); Outstream.println (""); Sendfile (outstream,file);//Send FileOutstream.flush (); } Else{//when the file does not existStringnotfound="<body>"; Outstream.println ("http/1.0404 No found"); Outstream.println ("content_type:text/html"); Outstream.println ("content_length:"+notfound.length () +2); Outstream.println ("");         Outstream.println (NotFound);        Outstream.flush (); }}Longm1=1;  while(m1<11100000) {m1++;}//DelayClient.close (); } Catch(IOException e) {System. out. println ("Exception:"+e); }}/*gets whether the request type is "get"*/Boolean getrequest (String s) {if(S.length () >0) {if(S.substring (0,3). Equalsignorecase ("GET"))return true; }return false; }/*get the file name to access*/string GetFileName (string s) {STRINGF=s.substring (S.indexof (' ')+1); F=f.substring (0, F.indexof ("')); Try{if(F.charat (0)=='/') F=f.substring (1); } Catch(stringindexoutofboundsexception e) {System. out. println ("Exception:"+e); }if(F.equals ("")) f="index.html"; returnF; }/*Sends the specified file to the Web browser*/       voidsendfile (Printstreamouts,file File) {Try{DataInputStreaminch=newdatainputstream (Newfileinputstream (file)); intLen= (int) file.length (); bytebuf[]=New byte[Len]; inch. readfully (BUF); Outs.write (BUF,0, Len);       Outs.flush (); inch. Close (); } Catch(Exception e) {System. out. println ("errorretrieving file."); System.exit (1); }}}

The Connectionthread line Cheng Zi class in the program is used to parse a request submitted by a Web browser and pass the reply back to the Web browser. where the Getrequest () method is used to detect whether the client's request is "get", and the GetFileName (s) method is to obtain the HTML file name to access from the customer request information S; Sendfile () method to pass the specified file contents back to the Web browser via the socket.

The Getrequest () method and related parts of the above procedure are modified, and the POST request can be processed.

Three, running example

In order to test the correctness of the above program, the compiled Webserver.class, Connectionthread.class, and the following index.html files are placed in the same directory as a host of the network (for example, the C:\JWEB directory of the host nt40srv).

Program 2:index.html File

<HTML>

<HEAD>

<metahttp-equiv= "Content-type" content= "text/html;charset=gb_2312-80" >

<title>java Web Server </TITLE>

</HEAD>

<BODY>

August 28, 1998

</BODY>

</HTML>

First run the Webserver.class with the Java command on the host:

C:\jweb>java webserver

Then, run the browser software at the client, and at the URL enter the URL address (for example: http://nt40srv:8080/index.html) that the webserver program belongs to, displaying the specified HTML document in the browser window.

Note that the default port number 8080 cannot be the default, and the host's normal Web server is running.

Description, you can test on a single machine that has Windows 95 installed without network conditions by using localhost or 127.0.0.1 instead of the domain name portion of the URL address, which is the URL address of http://localhost:8080

Web Request Response principle (GO)

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.