Java-based Web Server working mechanism (1)

Source: Internet
Author: User

Java-based Web Server working mechanism (1)

A Web server is also called an HTTP server because it uses http to communicate with its customers, who are usually browsers. A Java-based Web server uses two important classes:Java.net. socket andjava.net.ServerSocketAnd communicate through HTTP messages. At the beginning of this article, we will discuss HTTP and these two classes. Later, we will explain the working mechanism of a simple web server application.

Hypertext Transfer Protocol (HTTP)

HTTP allows servers and clients to receive and send data over the Internet. It is a request and response protocol-the client sends a request and the server responds to the request. HTTP uses a reliable TCP connection. The default TCP port is 80. The first version of HTTP is HTTP/0.9, which is subsequently replaced by HTTP/1.0. The latest version is HTTP/1.1, which is defined in the rpc2616 standard document.

This section briefly describes HTTP 1.1. It is sufficient for you to understand the messages sent by web server applications. For more information, see RFC 2616.

With HTTP, the client initializes the transaction session by establishing a connection and sending an HTTP request. The server contacts the client or responds to a callback connection to the client. Both of them can interrupt the connection. For example, when you use a web browser, you can click the stop button on the browser to stop the file download process, which effectively closes the HTTP connection to the web server.

HTTP Request (requests)

An HTTP request contains three parts:

  • Method, URL, protocol/version (method-Uri-Protocol/version)
  • Request headers
  • Entity package (entity body)

The following is an example of an HTTP request:

POST /servlet/default.jsp HTTP/1.1Accept: text/plain; text/html Accept-Language: en-gb Connection: Keep-Alive Host: localhost Referer: http://localhost/ch8/SendDetails.htm User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98) Content-Length: 33 Content-Type: application/x-www-form-urlencoded Accept-Encoding: gzip, deflate LastName=Franks&FirstName=Michael

The first line of the request is method-Uri-Protocol/version.

POST /servlet/default.jsp HTTP/1.1

The request is the POST method, followed/servlet/default.jspRepresents a URL address,HTTP/1.1Indicates the Protocol version.

The HTTP standard defines some request methods for each HTTP request. HTTP 1.1 supports the following request methods:GET,POST,HEAD,OPTIONS,PUT,DELETE, AndTRACE。 GETAndPOSTThe two most common methods are used in Internet applications.

A complete URI indicates an Internet resource. A URI is usually interpreted relative to the root directory of the server. Therefore, it always uses symbols (/. A URL is actually a URI type. The Protocol version indicates the version of the HTTP protocol currently in use.

The request header contains some useful information about the client environment and the entity body of the request. For example, it can contain the language and object length used by the browser. Each request header is separated by the CRLF (carriage return) sequence.

In the previous HTTP request, the entity is the following simple line:

LastName=Franks&FirstName=Michael

In a typical HTTP request, this entity can easily become longer.

HTTP Response (responses)

Similar to a request, an HTTP response also contains three parts:

  • Protocol Status Code Description (protocol-status code-description)
  • Response Header)
  • Entity body)

The following is a simple example of HTTP response:

HTTP/1.1 200 OKServer: Microsoft-IIS/4.0Date: Mon, 3 Jan 1998 13:13:33 GMTContent-Type: text/htmlLast-Modified: Mon, 11 Jan 1998 13:23:42 GMTContent-Length: 112

The response header of the first line is similar to the request header above. The first line tells us that the Protocol is http1.1, and the Response Request is successful (200 indicates that the request is successful), and everything is OK.

Response Headers are similar to request headers and contain useful information. The response entity is the content of the HTML part. Both the header and the object are separated by the CRLF sequence.

Socket

A socket is an endpoint of a network connection. It enables applications to read and write data over the network. By sending and receiving byte streams over connections, two software programs on different computers can communicate with each other. To send a message to another program, you need to know the IP address and socket Port Number of the target machine. In Java, a socket is composedJava.net. Socket class.

To create a socket, you can useSocket class constructor.These constructors accept host names and ports:

public Socket(String host, int port)

Host indicates the remote computer name or IP address,portIndicates the port number of the Remote Application. For example, to connect to Yahoo.com on port 80, You need to construct the following socket:

new Socket("yahoo.com", 80);

Once you have successfully createdSocketClass, you can use it to send and accept byte streams. To send a byte stream, you must first callSocketClassgetOutputStreamMethod to obtainjava.io.OutputStreamObject. To send a text to a remote application, you often need to constructOutputStreamObject returnedjava.io.PrintWriterObject. To receive the byte stream connected to the other end, callSocketClassgetInputStreamMethod, which is fromjava.io.InputStream.

The program section below creates a socket to communicate with the local HTTP server (127.0.0.1 represents a local), send an HTTP request, and then receive a response from the server. It createsStringBufferTo save the response and print it to the console.

Socket socket    = new Socket("127.0.0.1", "8080");OutputStream os   = socket.getOutputStream();boolean autoflush = true;PrintWriter out   = new PrintWriter( socket.getOutputStream(), autoflush );BufferedReader in = new BufferedReader(     new InputStreamReader( socket.getInputStream() ));// send an HTTP request to the web serverout.println("GET /index.jsp HTTP/1.1");out.println("Host: localhost:8080");out.println("Connection: Close");out.println();// read the responseboolean loop    = true;StringBuffer sb = new StringBuffer(8096);while (loop) {    if ( in.ready() ) {        int i=0;        while (i!=-1) {            i = in.read();            sb.append((char) i);        }        loop = false;    }    Thread.currentThread().sleep(50);}// display the response to the out consoleSystem.out.println(sb.toString());socket.close();

To get an exact response from the server, you need to send an HTTP request following the HTTP protocol rules. If you read the above section "Hypertext Transfer Protocol (HTTP)", you should be able to understand the code for establishing a socket just now.

Translated by willpower, 2003.11.23

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.