Eighth: Java network programming

xiaoxiao2021-03-06  40

Course index

Think before class 1. What is TCP / IP protocol? 2. Which two transport protocols are TCP / IP, what is the characteristics? 3. What is URL? 4. What kind of relationship is there in the URL and IP addresses? 5. What is a socket? 6. Socket (socket) and TCP / IP protocol relationship? 7. The relationship between URL and socket? 8.1 Network Programming Basic Concept, TCP / IP Protocol

8.1.1 Network Basics

The purpose of network programming is to communicate with other computers directly or indirectly over the network protocol. There are two main problems in network programming, one is how to accurately locate one or more hosts on the network, and the other is how reliable efficient data transmission after the host is found. In the TCP / IP protocol, the IP layer is mainly responsible for the location of the network host, the route of data transmission, and the IP address can uniquely determine a host on the Internet. The TCP layer provides an application-oriented reliable or non-reliable data transmission mechanism, which is the main object of network programming, which generally does not need to care about how the IP layer handles data. The currently popular network programming model is a client / server (C / S) structure. That is, the communication between the communication is waiting for the customer as a server to make a request and respond. The customer will apply to the server when the service is required. The server is generally running, listening to the network port as a daemon, and once a customer request will start a service process to respond to customers, while continuing to listen to the service port, making later customers to get timely service.

8.1.3 Two types of transfer protocols: TCP; UDP Although only TCP protocol names in the name of the TCP / IP protocol, there are two protocols of TCP and UDP at the same time in TCP / IP transport layers.

TCP is an abbreviation of Tranfer Control Protocol, a protocol that guarantees reliable transmission. The TCP protocol is transmitted to obtain a sequential errorless data stream. The two Sockets of the sender and the receiver must establish a connection to communicate on the basis of the TCP protocol. When a socket is waiting to establish a connection, another Socket can request a connection. Once these two sockets are connected, they can perform two-way data transmission, both sides can transmit or receive operations. UDP is the referusion of User DataGram Protocol. It is an unconnected protocol. Each datagram is a separate information, including a complete source address or destination address, which is passed on the network with any possible path to destination, Therefore, it is not possible to reach the destination, the time of arriving at the destination, and the correctness of the content cannot be guaranteed. Below we make simple comparison of these two protocols: When using UDP, complete address information is given in each datastumn, so there is no need to establish a connection to the sender and the receiver. For TCP protocols, because it is a connection-oriented protocol, it is necessary to establish a connection before data transmission between Socket, so there is a more connection established in TCP. When using UDP transfer data, there is a size limit, and each transmitted datagram must be limited to 64KB. The TCP does not have this limitations. Once the connection is established, the two sockets can transmit a large amount of data in a unified format. UDP is an unreliable protocol that does not necessarily reach the recipient in the same order. TCP is a reliable protocol that ensures that the recipient fully corrects all the data sent by the sender. In summary, TCP has strong vitality on network communication, such as remote connection (Telnet) and file transfer (FTP) require unpronant transmission of data. In contrast, the UDP operation is simple, and only less monitoring is required, and therefore it is usually used in the CLIENT / Server application in a dispersion system for high reliability of local area network. The reader may have to ask, since there is a TCP protocol that guarantees reliable transmission, why should it be non-reliable transfer UDP protocol? There are two main reasons. First, reliable transmission is to pay the price, and the test of the correctness of the data will inevitably take up the computer's processing time and network bandwidth, so the efficiency of TCP transmission is not as high as UDP. Second, in many applications, there is no need to ensure strict transmission reliability, such as video conferencing systems, do not require the audio video data absolutely correct, as long as the coherence can be, it is clear that UDP will be more reasonable. . 8.2 High-level Java Network Programming Based on URL

8.2.1 Consistent Resource Locator URL

URL (Uniform Resource Locator) is an uniform resource locator, which represents an address of a resource on the Internet. With URL we can access a variety of network resources on the Internet, such as the most common WWW, FTP site. The browser can find the corresponding file or other resources on the network by parsing a given URL.

8.2.2 Composition of URL

Protocol: // resourceEName protocol (Protocol) Indicates the transfer protocol used by the resource, such as HTTP, FTP, GOPHER, FILE, the resource name, should be the full address of the resource, including host name, port number, file A reference to the inside of the name or file. For example: http://www.sun.com/ Agreement Name: // Host Name http://home.netscape.com/home/welcome.html Protocol Name: // Machine name file name http: // www. Gamelan.com:80/gamelant/network.html#bottom protocol Name: // Machine name port number file name internal reference. 8.2.3 Create a URL

In order to express the URL, the class URL is implemented in java.net. We can initialize a URL object by the following constructor: (1) Public URL (String Spec); a URL object can be constructed by a string representing the URL address. URL URLBASE = New URL ("http: // www. 263.net/") (2) Public URL (URL Context, String Spec); constructs a URL object via group 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); New URL ("http", "www.gamelan.com", "/pages/gamelan.net. html"); (4) Public URL (String Protocol, String File); URL Gamelan = New URL ("http", "www.gamelan.com", 80, "pages / gamelan.network.html");

Note: Both the constructor of the class URL declares that the MalformedurLexception is discarded, so when you generate a URL object, we must process this exception, usually use the try-catch statement to capture. The format is as follows:

Try {url myurl = new url (...)} catch (Malformedurlexception E) {...}

8.2.4 Analysis of a URL

After a URL object is generated, its attribute cannot be changed, but we can get these properties by the methods provided by class URL: Public String getProtocol () Gets the protocol name of the URL. Public String gethost () Gets the host name of the URL. Public int getPort () Gets the port number of the URL, if the port is not set, return -1. Public string getFile () Gets the file name of the URL. Public String getRef () Gets the relative position of the URL in the file. Public String getQuery () Gets query information for this URL. Public string getPath () Gets the path of this URL PUBLIC STRING GETAUTHORITY () Gets the URL Permissions Information PUBLIC STRING GETUSERINFO () Gets the user's information public string getRef () Get the URL 8.2.5 Read the WWW network from the URL Resource

When we get a URL object, you can read the specified WWW resource by it. At this time, we will use the URL method OpenStream (), which is defined as: InputStream OpenStream (); method OpenSteam () establishes a connection to the specified URL and returns an object of the InputStream class to read data from this connection. Public class urlreader {public static void main (String [] args) throws exception {// declared all exceptions URL TIRC = New URL ("http://www.tirc1.cs.tsinghua.edu.cn/"); // construct a URL object BufferedReader in = new BufferedReader (new InputStreamReader (tirc.openStream ())); // openStream obtained using an input stream and thereby constructed a BufferedReader objects String inputLine; while ((inputLine = in.readLine ( )))! = NULL) // From the constant read data until system.out.println (InputLine) is read until the read data is printed on the screen in IN.CLOSE (// Close input Flow}}

8.2.6 Connect to the URLConnetction WWW

With the URL method OpenStream (), we can only read data from the network, if we also want to output data, such as sending some data to the server-side CGI program, we must first connect to the URL, then you can read it Write, then use the class URLConnection. CGI is a brief referred to as a common gateway interface. It is an interface for the user browser and server-side applications. For CGI programming, readers should be referred to the relevant books. Class URLConnection is also defined in the package java.net, which represents the communication connection between the Java program and the URL on the network. When a connection is established with a URL, you must first generate the corresponding URLConnection object on a URL object. For example, the following block first generates an object pointing to the address http://edu.chinaren.com/index.shtml, then opens a connection on the URL object with OpenConnection (), returns a URLConnection object. If the connection process fails, IOEXception is generated. Try {url netchchinaren = new url ("http://edu.chinaren.com/index.shtml"); urlconnectonnn tc = netchChinaren.openConnection ();} catch (mALFORMEDUREXCEPTION E) { // Creating a URL () object failed ...} catch (ieException e) {// OpenConnection () Failed ...} class URLConnection provides a lot of methods to set or get a connection parameters, and the most commonly used programming is getInputStream () and GetourPutstream (), It is defined as: InputSteram getInputSteram (); OutputSteram getOutputStream (); We can communicate with the remote object by returned input / output stream. Look at the example below: URL URL = New URL ("http://www.javasoft.com/cgi-bin/backwards"); // Create a URL Object UrlConnectin Con = URL.OpenConnection (); // By URL Object Get URLConnection object DataInputStream dis = new DataInputStream (con.getInputSteam ()); // URLConnection acquired by the input stream and configured DataInputStream objects PrintStream ps = new PrintSteam (con.getOutupSteam ()); // URLConnection acquired by the output stream, and Constructing the PrintStream object string line = disp.readline (); // reads a line PS.Println ("Client ...") from the server; // writes the string "Client ..." in the server, the BACKWARDS is the server-side CGI program. In fact, the method OpenSteam () of the class URL is implemented by URLConnection. It is equivalent to OpenConnection (). GetInputStream (); URL-based network programming is actually based on the SOCKET interface below.

Standardized network services such as WWW, FTP are based on TCP protocols, so in nature, URL programming is also an application based on TCP. 8.3 Low-level Java network programming based on Socket

8.3.1 Socket Newsletter

The two programs on the network implements data exchange through a two-way communication connection, and one end of this bidirectional link is called a socket. Socket is usually used to connect to the client and the server. Socket is a very popular programming interface of the TCP / IP protocol, and a socket is uniquely determined by an IP address and a port number. In the traditional UNIX environment, you can operate the TCP / IP protocol. There is no SOCKET, and the spectroductions supported by Socket are not only TCP / IP, so there is no inevitable connection between the two. In a Java environment, Socket programming is primarily based on network programming based on TCP / IP protocol.

8.3.2 General Process of Socket Communication

The general connection process of the CLIENT / Server programming is designed using Socket is: Server Listen (listening) Some ports have a connection request, the Client side issues a Connect (connection) request to the Server side, the Server is sent back to the client side back Accept (Accept) message. A connection is established. Server and Client ends can communicate with each other via Send, Write.

For a fully fully fully equipped socket, the following basic structure is included, and its work procedure contains the following four basic steps: (1) Creating a socket; (2) Open the input / outflow to connect to the socket; (3) Follow The protocol reads / writes Socket; (4) Close the Socket.

8.3.3 Creating a Socket

Java provides two class socket and serversockets in the package java.net, which are used to represent a two-way connection client and server. This is a very good class in two packages, which is very convenient. Configured 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 binddd, these address, Host and Port are the other IP addresses, host names, and port numbers in the two-way connection, and Stream indicates that Socket is a streaming Socket or a DITRPORT, LocalPort represents the port number, localaddr and bindaddr of the local host. Is the address of the local machine (the host address of the ServerSocket), IMPL is the parent class of the socket, which can be used to create ServerSocket and can be used to create a socket. COUNT indicates the maximum number of connections that the server can support. For example: Socket Client = New Socket ("127.0.01.", 80); Serversocket Server = New Serversocket (80); Note, you must be careful when selecting ports. Each port provides a specific service, only the correct port can be obtained. The port number of 0 ~ 1023 is preserved, such as the port number of the HTTP service is 80, the port number of the Telnet service is 21, the port number of the FTP service is 23, so we prefer a port number, it is best to choose a greater than 1023 Number of preventing conflicts. If an error occurs when you create a socket, IOException will be generated, and it must be processed in the program. So create a Socket or Serversocket is a must capture or throw an exception. 8.3.8 Simple Client / Server programming

Below we give a typical C / S structural demos of customers and servers implementing customers and servers, readers will have a more profound understanding of the concepts discussed earlier by carefully reading the program. Please refer to the comment in the meaning of the program.

1. Client program import java.io. *; import java.net. *; Public class talkclient {public static void main (string args []) {Try {socket socket = new socket ("127.0.0.1", 4700) ; // port 4700 to the client issuing the request native BufferedReader sin = new BufferedReader (new InputStreamReader (System.in)); // input device is configured by the system standard BufferedReader objects PrintWriter os = new PrintWriter (socket.getOutputStream ()); // Socket object obtained from the output stream, and configured PrintWriter object BufferedReader is = new BufferedReader (new InputStreamReader (socket.getInputStream ())); // Socket object obtained by the input stream, and the corresponding configuration of the object BufferedReader String readline; readline = SIN.Readline (); // Reads a string for a string while (! Readline.equals ("BYE")) {// stops the loop OS if the string read from the standard input is "BYE". Println (readline); // outputs the string read from the system standard into server Os.Flush (); // Refresh the output stream, so that Server will receive the string sostemtem.out.println ("Client:" Readline); // Print read string system.out.println on the system standard output ("Server:" is.readline ()); // Read a string from Server and print READLINE = SIN.Readline (); // from the system standard input reading a string} // Continue cycle (); // Close the socket output stream is.close (); // Turn the socket input Stream socket.close (); // Close Socket} catch (Exception E) {system.out.println ("Error" E); // Out, print error information}}}

2. Server-side program import java.io. *; import java.net. *; Import java.applet.applet; public class talkserver {public static void main (String args []) {Try {Serversocket Server = null; try { Server = New ServerSocket (4700); // Create a ServerSocket in port 4700 listening customer request} catch (exception e) {system.out.println ("can not listen to:" e); // error, print error message } Socket socket = null; try {socket = server.accept (); // uses accept () blocking waiting for the customer request, have a client // request to generate a socket object, and continue} catch (Exception E) {system .out.println ("error." e); // error, print error information} string line; buffreader is = new bufferedReader (socket.getinputstream ()); // is entered by the Socket object, and configuration corresponding BufferedReader objects PrintWriter os = newPrintWriter (socket.getOutputStream ()); // Socket object obtained from the output stream, and configured PrintWriter object BufferedReader sin = new BufferedReader (new InputStreamReader (System.in)); // the system Standard input device construction BUF FeredReader object

System.out.println ("Client:" is.readline ()); // Print the string LINE = Sin.Readline () read from the client on the standard output; // Read a character from the standard input String While ("BYE"))) {// If the string is "BYE", stop the cycle os.println (line); // Out of the string Os.Flush (); // Refresh the output stream so that the client immediately receives the string system.out.println ("Server:" line); / / Print read strings on the system standard output System.out.println ("Client: " is.readline ()); // read a string from the client and print it on the standard output line = sin.readline (); // Read a string from the system standard input} // Continue cycle OS .close (); // Turn the socket output stream is.close (); // Close the socket input stream socket.close (); // Close Socket Server.close (); // Close ServerSocket} catch (Exception E) { System.out.println ("Error:" E); // error, print error message}}} 8.3.9 Support multi-customer Client / Server programming

The Client / Server program provided earlier can only implement SERVER and a customer conversation. In practical applications, it is often running a permanent program on the server, which can receive requests from other clients to provide corresponding services. In order to achieve the functionality of the server to provide services to multiple customers, you need to transform the above program, and multithreading implements multiple client mechanisms. The server always listens to whether there is a customer request on the specified port. Once you listen to the customer request, the server will launch a special service thread to respond to the customer's request, and the server itself immediately enters the listening state after starting the thread. Waiting for the next customer's arrival.

ServerSocket serverSocket = null; boolean listening = true; try {serverSocket = new ServerSocket (4700); // Create a ServerSocket listening client on port 4700 requesting} catch (IOException e) {} while (listening) {// new monitor loop forever ServerThread (ServerSocket.accept (), clientnum) .Start (); // Monitor to the customer request, create a service thread based on the obtained Socket object and the customer count, and start the clientNum ; // increase customer count} Serversocket.close () ; // Close ServerSocket

Design ServerThread class

Public Class ServerThread Extends Thread {socket Socket = NULL; // Save the Socket Object with this thread INT ClientNum; // Save the customer count PUBLIC ServerThread (socket socket, int Num) {// Constructor this.socket = Socket; // Initialization Socket Variable ClientNum = Num 1; // Initialization ClientNum Variable} PUBLIC VOID RUN () {// Thread Main Try {/ / Here I achieve data acceptance and send} 8.3.10 Broadcast DataGram communication

When introducing the TCP / IP protocol, we have mentioned that in addition to the TCP protocol in addition to the TCP protocol, the UDP application is not as large as TCP, several standard applications The layer protocol HTTP, FTP, SMTP ... is all TCP protocols. However, with the development of the computer network, the UDP protocol is increasingly displayed, especially in an occasion that requires strong real-time interactivity, such as online games, video conferencing, etc., UDP is more showed Power, let's introduce how to implement UDP network transmission in the Java environment.

8.3.11 What is DataGram

The BRAGRAM will not guarantee reliable delivery, and the link-oriented TCP is better than the phone, and the two sides can affirm the other party to accept information. In front of this chapter, we have compared UDP and TCP, here again, slightly subsequent section: TCP, reliable, transmission size, but need to connect to establish time, error control overhead. UDP, unreliable, error control overhead is small, the transmission size is limited to 64K, and no connection is required.

8.3.12 DataGram communication representation: DataGramsocket; DataGrampacket

Both class DataGramsocket and DataGramsocket and DataGramPacket are used to support datagram, and DataGramsocket is used to establish a communication connection between programs, and DataGraMpacket is used to represent a datagram. Let's take a look at the construction method of DataGramsocket (); DataGramsocket (); DataGramsocket (int port, INTPETDRESS LADDR) where port indicates the port number used by Socket, if not specified in the port number, connect socket to the local A host on the host. Laddr indicates a available local address. When you give an port number, you must ensure that you do not have a port conflict, otherwise the Socketexception class exception is generated. Note: The above two constructors are declared to discard the exceptions of the unstart, and must be processed in the program, or capture, or declared abandonment. When writing a Client / Server program in a datagram, a DataGramsocket object is first established in the client or the service, first to receive or send datagrams, then use the DataGrampacket class object as a carrier for transferring data. Let's take a look at the construction method of DataGrampacket: DataGrampacket (Byte Buf [], INT Length; DataGrampacket (Byte Buf [], INT Length; inetaddress addr, int port); DataGrampacket (Byte [] BUF, INT Offset, INT longth; DataGrampacket (Byte [] BUF, INT Offset, INT Length; where the data is stored in the BUF, the length of the data is stored in the data report, and the addr and port destination address are indicated. The displacement amount is reported. Before receiving data, the first method of the above should generate a DataGrampacket object to give the buffer and length of the received data. Then call the DataGramsocket method receive () Waiting for the date of the datagram, Receive () will wait until a datagram is received. DataGrampacket Packet = New DataGrampacket (BUF, 256); Socket.Receive (Packet); While the buffer, the complete destination address is given, including the IP address and port number. The transmission data is implemented by the method Send () of the DataGramsocket, and Send () is recorded according to the destination address of the datagram to deliver the datagram. DataGrampacket Packet = New DataGrampacket (BUF, Length, Address, Port); Socket.send (Packet); To construct a datagram, you want to give an iNetAddress class parameter.

Class inetaddress is defined in the package java.net, used to represent an Internet address, we can get the IP address of the host by getting the type method that it provides the hostell name, and then get the corresponding address information . 8.3.14 Broadcast communication with datagram

DataGramsocket only allows the datagram to send a destination address, and a class MulticastSocket is provided in the Java.net package, allowing datagrams to be sent to all customers in the port in broadcast mode. MulticastSocket is used in the client, listens to the data from the server.

1. The client-side program: MulticastClient.java import java.io. *; import java.net *; import java.util *; public class MulticastClient {public static void main (String args []) throws IOException {MulticastSocket socket =.. New MulticastSocket (4446); // Create a 4446 port broadcast socket inetdress address = inetaddress.getbyName ("230.0.0.1"); // Get address information of 230.0.0.1 SOCKET.JOINGROUP (Address); // Using JOINGROUP () Bind the broadcast socket to the address of DataGrampacket Packet;

For (int i = 0; i <5; i ) {byte [] buf = new byte [256]; // Create buffer packet = new datagram (buf, buf.length); // Create a received datagram Socket. Receive (Packet); // Receive String Received = New String (Packet.getData ()); // Verified by the received data to the byte array, // and thus constructed a String object system.out.println (" Quote of themoment: " received); // Print Get String} // Loop 5 Socket.LeaveGroup (address); // Release the broadcast socket from the address to Socket.Close (); // Close broadcast socket}}}

2. Server program: Multicast Server.java public class multicastserver {public static void main (string args []) throws java.io iexception {new multicastServertHread (). Start (); // Start a server thread}}

3. Program MulticastServerThread.java import java.io. *; import java.net *;. Import java.util *;. Public class MulticastServerThread extends QuoteServerThread // get a new server MulticastServerThread thread class inherits from QuoteServerThread {Private long FIVE_SECOND = 5000 ; // Define constants, 5 seconds public multicastserverthread (String Name) "" MulticastServertHread "); // Call the parent class, which is the constructor of QuoteServerthread} public void run () // Rewind the parent class Thread main body {while (morequotes) {// Depending on the logo variable to continue cycle try {byte [] buf = new byte [256]; // Create buffer string dstring = null; if (in == null) dstring = new Date (). ToString (); // If the file is opened when the initialization is opened, the date is used as the string else dstring = getNextQuote (); / / otherwise call the member function to read the string from the file. BUF = dstring.getbyte (); // converts String into byte arrays to transmit send it inetaddress group = inetaddress.getbyname ("230.0.0.1"); // Get 230.0.0.1 address information DataGrampacket Packet = New DataGrampacket (BUF, BUF.LENGTH, GROUP, 4446); / / Create D according to buffer, broadcast address, and port number Atagrampacket object socket.send (packet); // Send this packet try {sleep ((long))); // Random Wait for a period of time, 0 ~ 5 seconds} Catch (InterruptedException E ) {} // abnormal handling} catch (ioException e) {// abnormal processing E.PrintStackTrace (); // Print error stack

Morequotes = false; // Set the end cycle sign}} Socket.close (); // Turn the broadcast set interface}}

[本 讲 小]

This story is mainly explained

Java

Network programming in the environment. because

TCP / IP

Agreement

Java

The basic knowledge of network programming, this is the focus of the opening.

TCP / IP

Some concepts in the agreement,

TCP / IP

The agreement itself is a very large system, which is impossible to use a few subts. So we just contact actual, explain some of the most basic concepts, help students understand the following related content. Focus on several concepts: host name,

IP

, Port, service type,

TCP

,

UDP.

Subsequent content is divided into two blocks, one is

URL

For the main line, explain how to pass

URL

Class and

UrlConnection

Access

WWW

Network resources, due to use

URL

It is very convenient and intuitive, although the function is not very strong, it is worth recommending a network programming method, especially for beginners. In essence,

URL

Network programming is still in the transport layer or

TCP

protocol.

Another piece is

Socket

Interface and

C / S

Network programming model is the main line, explain how to use

Java

Implementation

TCP

of

C / S

Structure, the mainly used class

Socket

,

Serversocket

. How to use

Java

Implementation

UDP

of

C / S

The structure also discusses a special transmission method, broadcasting method, this way

UDP

All of the class, the mainly used

DataGramsocket, DataGrampacket, MulticastSocket

. This piece

Java

It is the most difficult in network programming (although

Java

It has been made in this regard in network programming.

"

fool

"

However, the network programming is a very headache, and then

"

fool

"

Still have a certain difficulty), is also the most powerful part of the function

,

Readers should study and understand the ideas.

In the end, it is necessary to learn well.

Java

network programming,

Java

Language, most important thing is to practice!

转载请注明原文地址:https://www.9cbs.com/read-117734.html

New Post(0)