Java Network Programming

Source: Internet
Author: User

Thinking Before class
1. What is the TCP/IP protocol?
2. What are the two transmission protocols of TCP/IP? What are their respective characteristics?
3. What is a URL?
4. What is the relationship between URL and IP address?
5. What is Socket )?
6. What is the relationship between Socket and TCP/IP?
7. What is the relationship between URL and Socket?
8.1 basic concepts of network programming, TCP/IP Protocol Introduction

8.1.1 basic network knowledge
Network programming aims to communicate directly or indirectly with other computers through network protocols. There are two main problems in network programming: How to accurately locate one or more hosts on the network, and how to transmit data reliably and efficiently after finding the hosts. In TCP/IP, the IP layer is mainly responsible for locating network hosts and routing data transmission. The IP address can uniquely identify a host on the Internet. The TCP layer provides a reliable or unreliable data transmission mechanism for applications, which is the main object of network programming. Generally, you do not need to care about how the IP layer processes data.
Currently, the popular network programming model is the Client/Server (C/S) structure. That is, one Party serves as the server to wait for the customer to make a request and respond. The customer applies to the server when the service is required. The server is always running as a daemon and listens to the network port. Once a customer requests the server, a service process is started to respond to the customer. At the same time, the server continues to listen to the Service port, this allows later customers to get services in a timely manner.

8.1.3 two types of transmission protocols: TCP and UDP
Although the TCP/IP protocol name only has the TCP protocol name, both TCP and UDP protocols exist in the TCP/IP transport layer.
TCP is short for Tranfer Control Protocol. It is a connection-oriented Protocol that ensures reliable transmission. It is transmitted over TCP to obtain a sequential error-free data stream. The sender and receiver must establish a connection between two pairs of sockets to facilitate communication based on the TCP protocol. When a socket (usually a server socket) is waiting to establish a connection, another socket can require a connection. Once the two sockets are connected, they can perform bidirectional data transmission, and both parties can send or receive data.
UDP is short for User datasync Protocol. It is a connectionless Protocol. Each Datagram is an independent information, including the complete source address or destination address, it is transmitted to the destination in any possible path on the network. Therefore, the correctness of the arrival time, arrival time, and content cannot be guaranteed.
The following is a simple comparison of the two Protocols:
When UDP is used, the complete address information is provided in each datagram, so there is no need to establish a connection between the sender and the receiver. For TCP, because it is a connection-oriented protocol, a connection must be established before data transmission between sockets. Therefore, a connection is added in TCP.
When using UDP to transmit data, there is a size limit. Each transmitted datagram must be within 64 KB. TCP does not have such restrictions. Once the connection is established, the sockets of both parties can transmit a large amount of data in a unified format. UDP is an unreliable protocol. The data packets sent by the sender do not necessarily arrive at the receiver in the same order. TCP is a reliable protocol that ensures that the receiver fully and correctly obtains all data sent by the sender.
In short, TCP has a strong vitality in network communication. For example, remote connection (Telnet) and file transmission (FTP) both require indefinite data to be reliably transmitted. In contrast, UDP is easy to operate and requires less monitoring. Therefore, it is usually used for client/server applications in distributed systems with high LAN reliability.
Readers may ask, since there is a TCP protocol that ensures reliable transmission, why do we need a non-reliable UDP protocol? There are two main reasons. First, reliable transmission requires a price. The test of the correctness of data content will inevitably take up the processing time and bandwidth of the computer. Therefore, TCP transmission is not as efficient as UDP. Second, in many applications, strict transmission reliability is not required. For example, video conferencing systems do not require absolute correctness of audio and video data, as long as consistency is ensured, in this case, it is more reasonable to use UDP.

8.2 URL-based high-level Java Network Programming

8.2.1 consistent Resource Locator URL
A URL (Uniform Resource Locator) is the abbreviation of a consistent Resource Locator. It represents the address of a Resource on the Internet. Through URLs, we can access various network resources on the Internet, such as the most common WWW and FTP sites. By parsing a given URL, the browser can find the corresponding file or other resources on the network.
8.2.2 URL Composition

Protocol: // resourceName
The protocol name (protocol) indicates the transport protocol used to obtain resources, such as http, ftp, gopher, and file. The Resource Name (resourceName) should be the complete address of the resource, including a reference in the Host Name, port number, file name, or file. For example:
Http://www.sun.com/protocol name: // host name
Http://home.netscape.com/home/welcome.html protocol name: // machine name + file name
Http://www.gamelan.com: 80/Gamelan/network.html # BOTTOM protocol name: // machine name + port number + file name + internal reference

8.2.3 create a URL

To represent the URL, java.net implements the class URL. We can use the following constructor to initialize a URL object:
(1) public URL (String spec );
A URL object can be constructed using a string that represents the URL address.
URL urlBase = new URL ("http: // www. 263.net /")
(2) public URL (URL context, String spec );
Construct a URL object using the base URL and relative URL.
URL net263 = new URL ("http://www.263.net /");
URL index263 = new URL (net263, "index.html ")
(3) public URL (String protocol, String host, String file );
New URL ("http", "www.gamelan.com", "/pages/Gamelan.net. html ");
(4) public URL (String protocol, String host, int port, String file );
URL gamelan = new URL ("http", "www.gamelan.com", 80, "Pages/Gamelan.network.html ");

Note: The constructor of the class URL declares that the non-runtime exception (MalformedURLException) is discarded. Therefore, when generating a URL object, we must process this exception, it is usually captured using a try-catch statement. The format is as follows:

Try {
URL myURL = new URL (...)
} Catch (MalformedURLException e ){
...

}

8.2.4 parse a URL
After a URL object is generated, its attributes cannot be changed, but we can obtain these attributes through the method provided by the URL class:
Public String getProtocol () gets the protocol name of the URL.
Public String getHost () to obtain the Host Name of the URL.
Public int getPort () gets the port number of the URL. If no port is set,-1 is returned.
Public String getFile () gets the name of the URL file.
Public String getRef () gets the relative position of the URL in the file.
Public String getQuery () gets the query information of this URL.
Public String getPath () gets the URL path
Public String getAuthority () to obtain the URL permission information
Public String getUserInfo () get user information
Public String getRef () Get the URL's anchor

8.2.5 read WWW Network Resources from URLs

After we get a URL object, we can use it to read the specified WWW resource. In this case, we will use the URL method openStream (), which is defined as: InputStream openStream (); Method openSteam () establish a connection with the specified URL and return the InputStream class object to read data from this connection.

package com.ljq.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class URLReader {

public static void main(String[] args) throws Exception {
URL url = new URL("http://www.cnblogs.com/linjiqin/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
}

8.2.6 connect to WWW through URLConnetction

Through the URL method openStream (), we can only read data from the network. If we want to output data at the same time, such as sending some data to the CGI program on the server, we must first establish a connection with the URL before we can read and write it, then we need to use the URLConnection class. CGI is short for the Common Gateway Interface. It is an Interface connecting your browser and server applications. For CGI program design, see related books.

The URLConnection class is also defined in the java.net package, which indicates the communication connection between the Java program and the URL on the network. When establishing a connection with a URL, you must first generate the corresponding URLConnection object on a URL object through openConnection. For example, the following program section first generates an object pointing to the address http://www.cnblogs.com/linjiqin/. then, open a connection on the URL object with openconnection () and return a URLConnection object. If the connection fails, an IOException is generated.

Try {
URL netchinaren = new URL ("http://edu.chinaren.com/index.shtml ");
URLConnectonn tc = netchinaren. openConnection ();
} Catch (MalformedURLException e) {// An error occurred while creating the URL () object.
...
} Catch (IOException e) {// openConnection () failed
...
}

URLConnection provides many methods to set or obtain connection parameters. getInputStream () and getOurputStream () are most commonly used in programming. They are defined:
InputSteram getInputSteram ();
OutputSteram getOutputStream ();
Through the returned input/output stream, we can communicate with remote objects. See the following example:

Package com. ljq. test;

Import java. io. DataInputStream;
Import java. io. PrintStream;
Import java.net. URL;
Import java.net. URLConnection;

Public class URLReader {

Public static void main (String [] args) throws Exception {
// Create a URL object
URL url = new URL ("http://www.javasoft.com/cgi-bin/backwards ");
// Obtain the URLConnection object from the URL object
URLConnection conn = url. openConnection ();
// Obtain the input stream from URLConnection and construct the DataInputStream object
DataInputStream dis = new DataInputStream (conn. getInputStream ());
// Obtain the output stream from URLConnection and construct the PrintStream object.
PrintStream ps = new PrintStream (conn. getOutputStream ());
String line = dis. readLine ();
Ps. println ("client... "); // Write the string to the server" client... "
}
}

Backwards Is the CGI program on the server. In fact, the URL-like method openSteam () is implemented through URLConnection. It is equivalent to openConnection (). getInputStream ();
URL-based network programming is based on the Socket interface at the underlying layer. Standard network services such as WWW and FTP are all based on the TCP protocol, so URL programming is also an application based on TCP in essence.

8.3 Socket-based low-level Java Network Programming
8.3.1 Socket communication
Two programs on the network exchange data through a two-way communication connection. one end of this two-way link is called a Socket. Socket is usually used to connect the customer and the service provider. Socket is a very popular programming interface of TCP/IP protocol. A Socket is uniquely identified by an IP address and a port number.

In traditional UNIX environments, there are more than one Socket interface that can operate the TCP/IP protocol, and the Socket supports not only the TCP/IP protocol, therefore, there is no bound relationship between the two. In the Java environment, Socket programming mainly refers to network programming based on TCP/IP protocol.
8.3.2 General Socket communication process
The general connection process of using Socket for Client/Server programming is as follows: whether a port of the Server Listen (listener) has a connection request, and the Client sends a Connect (connection) to the Server) request. The Server sends an Accept (Accept) message back to the Client. A connection is established. Both the Server and Client can communicate with each other by sending, writing, and other methods.
For a fully functional Socket, it must contain the following basic structure. The working process includes the following four basic steps:
(1) create a Socket;
(2) Open the input/output stream connected to the Socket;
(3) perform read/write operations on the Socket according to certain protocols;
(4) Disable Socket.

8.3.3 create a Socket
Java provides two types of Socket and ServerSocket in the java.net package, which are used to represent the client and server for two-way connection respectively. These are two encapsulated classes that are very convenient to use. The construction method is as follows:
Socket (InetAddress address, int port );
Socket (InetAddress address, int port, boolean stream );
Socket (String host, int prot );
Socket (String host, int prot, boolean stream );
Socket (SocketImpl impl)
Socket (String host, int port, InetAddress localAddr, int localPort)
Socket (InetAddress address, int port, InetAddress localAddr, int localPort)
ServerSocket (int port );
ServerSocket (int port, int backlog );
ServerSocket (int port, int backlog, InetAddress bindAddr)
Here, address, host, and port are the IP address, host name, and port number of the other side of the two-way connection. stream indicates whether the socket is a stream socket or a datagram socket. localPort indicates the port number of the local host, localAddr and bindAddr are the addresses of local machines (the host address of ServerSocket), impl is the parent class of socket, which can be used to create both serverSocket and Socket. Count indicates the maximum number of connections supported by the server. For example:

Socket client = new Socket ("127.0.01.", 80 );
ServerSocket server = new ServerSocket (80 );
Note: Be careful when selecting a port. Each port provides a specific service. Only the correct port can be provided to obtain the corresponding service. 0 ~ The port number of 1023 is retained by the system. For example, the port number of the http service is 80, the port number of the telnet service is 21, and the port number of the ftp service is 23, it is best to select a number greater than 1023 to prevent conflicts.
If an error occurs during socket creation, an IOException is generated and must be processed in the program. Therefore, when creating a Socket or ServerSocket, exceptions must be caught or thrown.

8.3.8 simple Client/Server programming

The following is a demo of a typical C/S structure for customer-server interaction using Socket. The reader carefully reads this program, we will have a deeper understanding of the concepts discussed above. For the significance of the program, see annotations.

1. Client Program

2. server programs

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.