A brief analysis of the client-server interaction principle of Java Web Programs (RPM)

Source: Internet
Author: User

Reprinted from Http://www.cnblogs.com/lys_013/archive/2012/05/05/2484561.html

1. Agreement

A. Overview of the overall architecture of TCP/IP

The TCP/IP protocol does not fully conform to the OSI seven-layer reference model. The traditional open System Interconnect Reference Model is a 7-layer abstract reference Model for communication protocols, where each layer performs a specific task. The purpose of this model is to enable various hardware to communicate with each other at the same level. These 7 layers are: Physical layer, Data link layer, network layer, transport layer, Session layer, presentation layer and application layer. The TCP/IP protocol uses a 4-tier hierarchy, each of which calls the network provided by its next layer to fulfill its own needs. These 4 layers are:

I. Application layer: Layers of communication between applications, such as Hypertext Transfer Protocol (HTTP), simple e-mail Transport (SMTP), File Transfer Protocol (FTP), Network Remote Access Protocol (Telnet), and so on.

II. Transport layer: In this layer, it provides data transfer services between nodes, such as Transmission Control Protocol (TCP), User Datagram Protocol (UDP), and so on, TCP and UDP to the packet into the transmission of data and transfer it to the next layer, this layer is responsible for transmitting data, and to determine that the data has been delivered and received.

III. Interconnection Network layer: responsible for providing basic data packet transfer function, so that each packet can reach the destination host (but not check whether it is received correctly), such as Internet Protocol (IP).

Iv. Network Interface layer: the management of the actual network media, define how to use the actual network (such as Ethernet, Serial line, etc.) to transfer data.

B. Introduction to the HTTP protocol:

I. HTTP is a Hypertext Transfer Protocol (hypertext Transfer Protocol), which is a set of rules for computers to communicate in a network. In the TCP/IP architecture, HTTP belongs to the application-layer protocol, at the top level of the TCP/IP protocol

II. HTTP is a stateless protocol that means that there is no need to establish a persistent connection between a Web browser (client) and a Web server. The whole process is when a client sends a request to the server, and then the Web server returns a response (response), then the connection is closed and the connection is not retained at the end of the service.

III. HTTP follows the request/response (Request/response) model, and all communication interactions are constructed in a set of request and response models.

Iv. when browsing the web, the browser exchanges information with the Web server through the HTTP protocol, and the files returned by the Web server to the Web browser have types associated with them, and the format of the information types is defined by MIME.

C. Java implementation of the Protocol

Whether it is TCP/IP protocol or HTTP protocol, Java is through the socket (java.net.Socket) to achieve, you can refer to another technical blog: A project look at Java TCP/IP Socket programming (version 1.3)


2. HTTP message interface and client and server-side interaction principles

A. HTTP-defined transactions consist of the following four steps:

I. Establish a connection:

For example, when I enter http://cuishen.iteye.com in a browser, the client requests this address by opening a socket on the Web server HTTP port. Because in the middle of the network as the transmission of data is the physical media is the network cable, the data is essentially through the IO stream output and input, it is not difficult to understand why we write a servlet to reference the import java.io.*; , including the println () method of the PrintWriter object when we send the results back to the client. In fact, the address of the request to add the port number 80,80 can not write, because the default browser port number is 80.

This is true in Java's underlying code, except that they have done it for us.

New Socket ("cuishen.iteye.com");  2.InputStream in = socket.getinputstream ();  3.OutputStream out = Socket.getoutputstream ();   

II. Client sending HTTP request message (requests)

Once a TCP connection is established, the Web browser sends a request command to the Web server, which is an ASCII text request line followed by 0 or more HTTP headers, a blank line, and any data that implements the request.

That is, the message is divided into four parts: the request line, the request header, the blank line and the request data

1) Request Line

A request line consists of three tokens: The request method, the request URL, and the HTTP version, separated by a space

Example: GET cuishen.iteye.com/blog/242842 http/1.1

The HTTP specification defines 8 possible request methods: (most commonly, GET and POST two methods)

GET--Retrieves a simple request to identify a resource in the URI
Head--Same as the Get method, the server returns only the status line and header, and does not return the requested document
POST--The server accepts requests that are written to data in the client output stream
PUT--The server holds the request data as a request for the new content of the specified URI
Delete--The server deletes a request for a resource named in the URI
OPTIONS-Requests for information about request methods supported by the server
TRACE--Web server feedback HTTP request and its header request
CONNECT-a method that has been documented but not currently implemented, reserved for tunnel processing

2) Request Header

Request Header: Consists of key:value health values, one pair per line. The request header is used to inform the server about the functionality and identity of the client.

Host--which server-side address and primary address is requested, for example: my technical blog:cuishen.iteye.com
User-agent-The user is the browser that the client can use, such as: mozilla/4.0
Accept--a list of MIME types that the client can accept, such as Image/gif, text/html, Application/msword
Content-length--Applies only to post requests, in bytes gives the size of the post data

3) Blank line

Send carriage returns and regressions, notifying the server that the header is no longer available.

4) Request data

Using post to transmit data, the most commonly used is the Content-type and content-length headers.


Request Message Summary:

We can write a standard HTTP request like this:

post/blog/242842 HTTP1.1
host:cuishen.iteye.com/
user-agent:mozilla/4.0
Accpt:image/gif,text/html,application/pdf,image/png ...
Key=value&key=value&key=value ... (POST () requested data)

An example of this above means:

The server-side address I'm going to visit is cuishen.iteye.com/resources under it/blog/242842
Connected together: cuishen.iteye.com/blog/242842
This page is using the HTTP1.1 specification, my browser version is mozilla/4.0
The MIME format that can be supported is image/gif,text/html,application/pdf,image/png ... Wait a minute

The MIME format we are writing in the servlet is: Response.setcontenttype ("text/html;charset=gb2312");
Or in JSP, the wording is: <%@ page contenttype= "text/html;charset=gb2312"%>
or the wording in HTML is: <meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">

The most intuitive difference between get and POST is that the Get method follows the requested URL, which is what we do in the request line:

Get/blog/242842?key=value&key=value&key=value ... HTTP1.1

Actually, the data is passed in this way with GET:

http://cuishen.iteye.com/?page=2 ...


Iii. server-side response requests generate results and postback (response)


The WEB server resolves the request and locates the specified resource http://cuishen.iteye.com/blog/242842


1) According to the get/post of the request, the doget ()/DoPost () method in the servlet is used to deal with (there may be some business logic, there may be some validation, and so on, there may be some data query, submit, etc.) its valid data is derived from Key=value &key=value&key=value ..., and some other data resources encapsulated in the request object.


2) After processing the request, the response object gets the Java.io.PrintWriter output stream object out, through the out.println (); Outputs the data to the output stream in the specified format, such as in accordance with Response.setcontenttype ("text/html;charset=gb2312");

Its response message is very similar to the request message, and the difference is that the request line in the request phase is replaced by the state line, and then the response message:


3) A response message consists of four parts: status line, response header, blank line, response data:

(a). Status line:

The status line consists of three tokens: HTTP version, response code, and response description.

HTTP1.1------continue//continuation of subsequent additions
HTTP1.1------OK//All normal
HTTP1.1---301---Moved permanently//requested documents are automatically connected elsewhere
HTTP1.1---403---Forbidden//absolutely deny you access to this resource, whether authorized or not
HTTP1.1------bad syntax in Request//client requests
HTTP1.1---404---not Found//The most common, is definitely the famous can't find

HTTP response code:

1XX: Informational message that tells the client to respond to certain other actions
2XX: These represent the success of the request
3xx: Redirect, in order to complete the request, the action must be further performed
4XX: Client Error
500-599: Server-side error

(b). Response headers: Like request headers, they indicate the functionality of the server and identify the details of the response data.

Date:sat, Dec 2005 23:59:59 GMT-the date and time the response was generated
ContentType: ' text/html;charset=gb2312 '
content-length:122-The number of bytes in the response, only required when the browser is using a permanent (keep-alive) HTTP connection.

(c). Blank line: The last response header is followed by a blank line, which sends a carriage return and a regression indicating that the server no longer has a header label.

(d). Response data: HTML documents and images, and so on, the HTML itself. Out.println ("&LT;HTML&GT; ..."); Write to client.

1.<Html>2.<Head>3.<Title>welcome to Cuishen ' s IT blog</title> 4.</head> 5.< Span style= "color: #0000ff;" ><body> 6.<!-- here is the concrete content that is seen here in 7. I'm sure you know how HTTP works and the client-server interaction process is clear. 8.--> 9. </body> 10.< Span style= "color: #0000ff;" ></html>       

Iv. server-side shutdown connection, client resolution postback response message, Recovery page

1) The browser parses the status line first to see if the request is successful status Code--http response code: 404 400 200 ....

2) Resolve each response header, such as:

contenttype:text/html;charset=gb2312
content-length:122---The number of bytes in the response, only required if the browser is using a permanent (keep-alive) HTTP connection.

3) Read the response data HTML, restore the standard HTML format page or other according to the contents of the tag

4) An HTML document may contain other resources that need to be loaded, the browser will recognize it and make additional requests for those resources, and the process can be looping all the way up to the time that all the data is restored to the page in the format specified in the response header.

5) The data transfer is complete, the server side closes the connection, namely the stateless Protocol.

3. Summary

Do not be intimidated by the advanced terminology and theory, in fact, the HTTP client and server-side interaction principle is simple: that is, the browser and server-side to establish a socket stateless connection, that is, a short connection, and then through the IO stream for message information (this message is strictly follow the HTTP message interface) of the interaction, Close the connection after the last session is finished. For these low-level protocols and packets of packet unpacking interaction implementation, in fact, Java and the browser has already encapsulated, programmers just focus on the implementation of the business logic is OK, these do not have to care!!

A brief analysis of the client-server interaction principle of Java Web Programs (RPM)

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.