Java Network Programming, java Network Programming pdf

Source: Internet
Author: User

Java Network Programming, java Network Programming pdf

We usually browse some news and watch videos through WEB browsers every day.

As we all know, this is the so-called B/S structure (Browser/Server, Browser/Server mode). It is a network structure mode after the rise of WEB, WEB browsers are the most important application software on the client.


Let's take a simple look at the basic implementation principles of the so-called Web servers (such as well-known Tomcat) and browsers?

First of all, we can make it clear that, for example, we enter an address in a browser to access a webpage.

The actual underlying operations are simply the network communication between the client (browser) and WEB servers.

Therefore, it is network communication. Corresponding to Java, Socket and IO streams are naturally inseparable. In fact, this is also the basic implementation principle of Web servers and browsers.

Of course, it is complicated to develop a complete set of WEB servers or browsers. But here, what we want to know is its principle.


We know that after deploying the developed web project to the tomcat server, you can access the resources on the server through a browser.

However, it is important that different browsers developed by different vendors exist. However, all types of WEB browsers can normally access resources on the tomcat server.

We can understand this as follows: I have developed a WEB server and can ensure that clients developed by others can communicate with my server normally.

The premise for achieving this goal is naturally that you need to develop a specification and follow this specification for clients that want to communicate normally with your developed server.

This specification is also called a protocol.


Therefore, in network communication, data transmission can follow the TCP/IP or UDP protocol.

The WEB Server communicates with the WEB browser in a language that both parties are familiar.

This Protocol is Hypertext Transfer Protocol (HTTP.

The difference is that TCP/IP and UDP are the communication protocols in the transport layer, while HTTP is the protocol in the application layer.


Therefore, when we want to use Java to implement the so-called WEB communication, we should naturally follow the HTTP protocol.

Java provides us with such an implementation specification, that is, the widely known Servlet interface.

When developing a web project, the most common HttpServlet class is the specific subclass implemented based on this interface.

This class encapsulates and provides common methods for accessing and operating Http-based content.

After talking about this, we can use some small instances to make it easier to understand the image.


First, let's look at the request information for WEB communication based on HTTP through a simple Servlet code:

public class ServletTest extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {String header = (String) e.nextElement();if (header != null)System.out.println((new StringBuilder(String.valueOf(header))).append(":").append(request.getHeader(header)).toString());}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}}
In the above Code, we aim to use the method in HttpSerlvetRequest,

To print the details of the encapsulated http request initiated by the web browser based on the HTTP protocol. The output result of the program is as follows:



An HTTP request usually consists of three parts:

  • Method/Uniform Resource Identifier (URI)/protocol/version
  • Request Header
  • Entity

The method is also called a get/post request method. The Uniform Resource Identifier is the path of the target resource to be accessed, including the protocol and Protocol version, this information is placed in the first line of the request.

Then, the request header is followed. The request header usually contains useful information related to the client environment and the Request Entity.

Finally, there is a blank line between the header and the entity body. It is very important for the HTTP request format. blank lines tell the HTTP server that the entity starts from here.


As mentioned above, what we want to study here is the basic implementation principle of WEB servers.

We naturally want to implement the so-called WEB server by ourselves. We already know:

The so-called B/S structure is actually a network communication between the client and the server based on the HTTP protocol.

Therefore, socket and I/O are indispensable. Therefore, we can simulate a shanzhai browser with the simplest functions:

Public class MyTomcat {public static void main (String [] args) {try {ServerSocket tomcat = new ServerSocket (9090); System. out. println ("server startup"); // Socket s = tomcat. accept (); // byte [] buf = new byte [1024]; InputStream in = s. getInputStream (); // int length = in. read (buf); String request = new String (buf, 0, length); // System. out. println (request);} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}
This time, we access our shanzhai server through the corresponding URL in the browser. The output result is:


Through the results, we can see that we have successfully copied tomcat.

However, it should be noted that the reason why we successfully output the Http Request body in our own tomcat server is:

We access through a web browser. If we access serversocket through a common socket, there is no such request information.

As we have already said before, the communication between web browsers and servers must follow the Http protocol.

Therefore, the web browser we use in our daily life automatically packs our requests based on the http protocol.


However, because we have already understood the principles, we can also simulate browser preferences:

// Shanzhai browser public class MyBrowser {public static void main (String [] args) {try {Socket browser = new Socket ("192.168.1.102", 9090 ); printWriter pw = new PrintWriter (browser. getOutputStream (), true); // encapsulate the first row of the Request pw. println ("GET/HTTP/1.1"); // encapsulate the request header pw. println ("User-Agent: Java/1.6.0 _ 13"); pw. println ("Host: 192.168.1.102: 9090"); pw. println ("Accept: text/html, image/gif, image/jpeg, *; q =. 2, */*; q =. 2" ); Pw. println ("Connection: keep-alive"); // empty rows pw. println (); // encapsulate the Object Body pw. println ("UserName = zhangsan & Age = 17"); // the browser is written. shutdownOutput (); // receives the message returned by the server, InputStream in = browser. getInputStream (); // int length = 0; StringBuffer request = new StringBuffer (); byte [] buf = new byte [1024]; // while (length = in. read (buf ))! =-1) {String line = new String (buf, 0, length); request. append (line);} System. out. println (request); // browser. close ();} catch (IOException e) {System. out. println ("abnormal, fuck! ");} Finally {}}// modified shanzhai tomcat server public class MyTomcat {public static void main (String [] args) {try {ServerSocket tomcat = new ServerSocket (9090); System. out. println ("server startup"); // Socket s = tomcat. accept (); // byte [] buf = new byte [1024]; InputStream in = s. getInputStream (); // int length = 0; StringBuffer request = new StringBuffer (); while (length = in. read (buf ))! =-1) {String line = new String (buf, 0, length); request. append (line);} // System. out. println ("request:" + request); PrintWriter pw = new PrintWriter (s. getOutputStream (), true); pw. println ("

Start the server first, and then run the browser to simulate the Web browsing process. First, we can see the request information received by the server:



Then, after receiving the request for processing, the server returns the resource to the browser and gets the output information:


We can see that the returned information in the shanzhai browser is actually the source code of an HTML file,

In our shanzhai browser, this information is only displayed in plain text because our shanzhai browser does not have the ability to parse the HTML language.

Therefore, another important function of the browser is to parse hypertext markup language. In fact, this is also the difficulty and focus of browser development.


The output above looks obviously uncomfortable, so it is difficult to say that the products in shanzhai are not empty!

We tried to access our shanzhai server through a regular WEB browser and found that the effect was far greater:

By the way, when a browser initiates an access request to a WEB server, it encapsulates the corresponding HTTP Request body.

Then, when the WEB server finishes processing browser requests and returns data, it will also encapsulate the HTTP response body.

For example, if we modify the code of our shanzhai browser to connect to the real tomcat server:

Public class MyBrowser {public static void main (String [] args) {try {Socket browser = new Socket ("192.168.1.102", 8080); PrintWriter pw = new PrintWriter (browser. getOutputStream (), true); // encapsulate the first row of the Request pw. println ("GET/HTTP/1.1"); // encapsulate the request header pw. println ("User-Agent: Java/1.6.0 _ 13"); pw. println ("Host: 192.168.1.102: 8080"); pw. println ("Accept: text/html, image/gif, image/jpeg, *; q =. 2, */*; q =. 2 "); pw. println ("Con Nection: keep-alive "); // empty rows pw. println (); // encapsulate the entity body // pw. println ("UserName = zhangsan & Age = 17"); // the browser is written. shutdownOutput (); // receives the message returned by the server, InputStream in = browser. getInputStream (); // int length = 0; StringBuffer request = new StringBuffer (); byte [] buf = new byte [1024]; // while (length = in. read (buf ))! =-1) {String line = new String (buf, 0, length); request. append (line);} System. out. println (request); // browser. close ();} catch (IOException e) {System. out. println ("abnormal, fuck! ") ;}Finally {}}}
Run the program and you will send the following output information:


Similar to HTTP requests, an HTTP response usually contains three parts:

  • Protocol/response code/status description: The Protocol refers to the HTTP protocol information, response Code refers to the code representing the processing result of the request (for example, 200, 404, 500). It is actually the response description of the request processing.
  • Response Header: The response header also contains useful information similar to the header in the HTTP request.
  • Response entity: Usually the HTML content of the response.

Like an HTTP request, a blank line is also used between the response header and the response object to facilitate interpretation.

At the same time, we can also find that the content that is actually parsed and displayed on the browser webpage is actually only a part of the response entity.

In response lines and response headers, some useful information is actually returned to us, but this part does not need to be displayed in the browser.

That is to say, in addition to the ability to obtain a complete HTTP response, our browser should also be able to parse the HTTP response.


In fact, Java also provides us with such an object, namely the URL and URLConnection object.

If we implant such an object in our shanzhai browser to perform HTTP Communication with the server, then:

public class MyBrowser2 {public static void main(String[] args) {try {URL url = new URL("http://192.168.1.102:8080");HttpURLConnection conn = (HttpURLConnection) url.openConnection();InputStream in = conn.getInputStream();byte[] buf = new byte[1024];int length = 0;StringBuffer text = new StringBuffer();String line = null;while ((length = in.read(buf)) != -1) {line = new String(buf, 0, length);text.append(line);}System.out.println(text);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
This time, when we run the program again and view the output information, we find that the input stream we obtained from the URLConnection object is,

The response information we read is as expected, leaving only the content of the response entity to be parsed and displayed on the page.

In fact, this is the object that Java provides for us. It encapsulates the parsing function of HTTP content.

Basically, we can imagine that URLConnection = Socket + HTTP parser.

That is to say, the underlying layer of the object not only connects to the WEB server through Socket, but also encapsulates the parsing function for HTTP content.


At this point, we have briefly understood the basic implementation principles of WEB servers and browsers.

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.