Eighth: Java network programming

zhaozj2021-02-16  56

8.1 Basic Concept of Network Programming, TCP / IP Protocol

8.1.1 Network Basics

Computer network is diverse, complicated in content. Computers on the network must communicate with each other and must follow certain protocols. The most widely used network protocol current is the TCP / IP protocol used on the Internet.

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.2 Network Basic Concept

IP address: Identify network addresses of network devices such as computers, composed of four 8-bit binary numbers, separated by decimal points. Such as: 166.111.136.3, 166.111.52.80

Hostname: Help Name of the network address, grade the domain name. Such as: www.fanso.com port number: ID of different processes on the same machine when network communication. Such as: 80, 21, 23, 25, wherein 1 to 1024 is a port number service type (Service) reserved for the system: the various services of the network. HTTP, TELNET, FTP, SMTP We can describe the following concepts we mentioned here:

On the IP address and host name on the Internet, you can get the IP of the machine by domain name analysis, because the machine name is closer to the natural language, easy to remember, so use a wide range of IP, but the machine is only The IP address is a valid identifier.

Usually there are always many processes on a host to require network resources for network communication. The importance of network communication is not the host, but should be the process running in the host. At this time, light has a host name or IP address to identify that many processes are obviously not enough. The port number is to take a means of providing more network resources on a host, which is also a mechanism provided by the TCP layer. Only a combination of host name or IP address and port number can only determine the object in the network communication: process.

The type of service is the concept of the application layer above the TCP layer. The TCP / IP protocol can construct a variety of complex applications, and the type of service is the application that has been standardized, usually the web server (software). Readers can write their own network-based servers, but they cannot be called standard service types. 8.1.3 Two types of transport 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.

URL is the most intuitive network positioning method. Using the URL in line with people's language habits, it is easy to remember, so the application is very extensive. And in the most widely used TCP / IP, the resolution of the hostname in the URL is also a standard of the protocol, that is, the so-called domain name resolution service. Use the URL to make a network programming, do not need too much understanding of the agreement itself, the function is relatively weak, so it is relatively simple, so we will introduce how to use the URL in Java to guide the reader to introduce the reader. 8.2.2 The consisting of the 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 A reference, port number, file name or file inside. 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 port number is a concept related to Socket programming, beginners don't have to be deep, in the back There is a detailed explanation. The internal reference is the tag in HTML, and interested readers can refer to books about HTML.

8.2.3 Creating a URL To represent 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, String File); 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) {... // exception handler code he ...} 8.2.4 Western URL A URL object is generated, its attribute is not changed, but we can pass The methods provided by class URLs are used to get these properties: Public String getProtocol () Gets the name of the protocol 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 the URL PUBLIC STRING GETAUTHORITY () Gets the permissions of the URL PUBLIC STRING GETUSERINFO () Get the user's information public string getRef () Get the anchor of the URL

In the following example, we generate a URL object and get the individual properties.

Import java.net. *; import java.io. *;

Public class parseurl {public static void main (string [] args) throws exception {

URL AURL = New URL ("http://java.sun.com:80/docs/books/"); URL TUTO = New URL (AURL, "Tutorial.Intro.html # Download"); System.Out.println ("protocol =" tuto.getProtocol (); system.out.println ("host =" tuto.get ()); system.out.println ("filename =" tuto.getfile ()); system .out.println ("port =" tuto.get ()); system.out.println ("ref =" tuto.getRef ()); system.out.println ("query =" tuto.getQuery ))); System.out.println ("path =" tuto.getPath ()); system.out.println ("userinfo =" tuto.getuserinfo ()); system.out.println ("authority =" Tuto.getAuthority ());}}

Execution: protocol = http host = java.sun.com filename = / DOCS / BOOKS / TUTORIAL.INTRO.HTML port = 80 ref = Download Query = NULL PATH = / DOCS / BOOKS / TUTORIAL.INTRO.HTML UserInfo = NULL Authority = java.sun.com: 808.2.5 Read WWW Network Resources from URL

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 will be generated.

Try {url netchChinaren = new url ("http://edu.chinaren.com/index.shtml"); urlConnectonn TC = NetChinaren.openConnection ();} catch (mALFORMEDURLEXCEPTION E) {// Create URL () object failed ... } Catch (IOException E) {// OpenConnection () Failed ...} Class URLConnection provides many ways to set or get connection parameters, and the most commonly used GetourPutStream () and getourPutStream (), which are defined as: InputSteram getInputSteram (); OutputSteram getOutputStream ();

We can communicate with the remote object by returning 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 (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.

Saying Socket programming is low-level network programming is not equal to its function is not strong. It is just the opposite, because of the low level, Socket programming is more powerful and more flexible than the URL-based network programming, but it is more complex. . Due to the particularity of Java itself, Socket programming in Java may already be a minimum network programming interface in Java. In Java, you need to directly operate the lower level in the protocol, you need to use Java's local method call (JNI), here is not Discuss it. 8.3.2 General Process of Socket Communication It has been mentioned in front of Socket usually used to implement a C / S structure.

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.

The third step is the key steps for programmers to call Socket and implement program features, and other three steps are basically the same in various programs. The above four steps are for TCP transmission, which is slightly different when transmitting using UDP, and there will be specifically explained it later.

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 bindaddr)

Among them, Address, Host and Port are the other IP addresses, host names, and port numbers in the two-way connection. Stream indicates that Socket is a streaming Socket or a datagram socket, localport represents the port number of the local host, localaddr and bindaddr are the address of the local machine ( ServerSocket host address), IMPL is the parent class of 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.4 Client's Socket Below is a typical process of creating client sockets. Try {socket socket = new socket ("127.0.0.1", 4700); //127.0.0.1 is the default native address in the TCP / IP protocol} catch (ioException e) {system.out.println ("Error:" E);

This is the easiest way to create a socket in the client, but also the first step in using socket for network communication, the program is quite simple, and there is no explanation here. This small program segment is used in the later program.

8.3.5 Server SERVERSOCKET below is a typical process for creating a Server-side ServerSocket. ServerSocket Server = NULL; try {server = new serversocket (4700); // Create a ServerSocket in port 4700 listening customer request} catch (ioException e) {system.out.println ("can not listen to:" e); } Socket socket = null; try {socket = server.accept (); // accept () is a blocking method, once there is a customer request, it returns a socket object to interact with the customer} Catch (IOException E ) {System.out.println ("Error:" E);

The above procedure is a typical working mode of Server, but the server can only receive a request. After receiving it, Server is exited. In actual applications, it always allows it to receive loop reception. Once there is a customer request, Server always creates a service thread to serve new customers, and continue to listen. ACCEPT () is a blocking function, so that after the method is called, the client will wait for the customer's request until a customer starts and requests to connect to the same port, and then accept () returns a customer corresponding to the customer Socket. At this time, both the client and the service have established a socket for communication, which is the respective input / output streams by each Socket. 8.3.6 Open Input / Export Class Socket provides methods getInputStream () and getOutStream () to get the corresponding input / output stream for read / write operation, which returns the INPUTSTREAM and OUTPUTSTEAM class objects. To facilitate reading / write data, we can create filter flows on the return input / output stream object, such as DataInputStream, DataOutputStream or PrintStream class object, and for text-flow objects, INPUTSTREAMREADER and OUTPUTSTREAMWRITER, PRINTWIRTER and other processing can be used.

For example: PrintStream os = new PrintStream (new BufferedOutputStreem (socket.getOutputStream ())); DataInputStream is = new DataInputStream (socket.getInputStream ()); PrintWriter out = new PrintWriter (socket.getOutStream (), true); BufferedReader in = New ButffReader (new input.getinputstream ()));

The input and output stream is a substantial part of the network programming, and how to construct the desired filter flow, to be determined as needed, can be used to primarily see the reader's input and output part of Java.

8.3.7 Close Socket

When each socket exists, you will take up a certain resource. When the Socket object is used, it is closed. Turn off the socket to call the CLOSE () method of the socket. All input / output streams associated with socket should be turned off before shutting down sockets to release all resources. Moreover, pay attention to the sequence of closing, all input / output related to socket, then turn off, then close the socket. Os.close (); is.close (); socket.close ();

Although Java has an automatic recycling mechanism, network resources will eventually be released. However, in order to effectively utilize resources, it is recommended that readers actively release resources in a reasonable order.

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.

Client program

2. Server-side 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 issued the client's requests BufferedReader sin = new BufferedReader (new InputStreamReader (System.in)); // input device is configured by the system standard BufferedReader objects PrintWriter os = new PrintWriter (socket.getOutputStream ()); // the Socket object to obtain an 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 () ; // Read a string from the system standard for a string while (! Readline.e ")) {// Stop cyclic OS.println (Readline) if the string read from the standard input is" BYE "; // Output the string read from the system standard to Server Os.Flush (); // Refresh the output stream so that Server will immediately receive the string system.out.println ("Client:" readline); / / Print read string system.out.println ("Server:" is.readline ()); // read a string from Server and print it on the standard output Readline = sin.readline (); // Read a string from the system standard input} // Continue loop OS.Close (); // Turn the socket output stream is.close (); // Close the Socket input stream Socket. Close (); // Close Socket} catch (Exception E) {system.out.println ("ERROR" E); // error, print error message}}} 2. server server

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 to customer request} catch (Exception E) {system.out.println ("can not listen to:" e); // error, print error message} Socket Socket = Null Try {socket = server.accept (); // Using accept () blocking waiting for a customer request, a client // request arrives generates a socket object, and proceeds to execute} catch (Exception E) {system.out.println "Error." E); // error, print error information} String line; buffredreader is = new buffredReader (new input.getInetInPutStream ())); // Get the input stream by the Socket object, and construct the corresponding bufferedReader Object 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 configured BufferedReader 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}} We can see the use of four steps from the two programs from above. The reader can select the corresponding block of the four steps used by Socket, so that the reader has a further understanding of the use of Socket.

The reader can test the program on a stand-alone, it is best to test the program in a real network environment, which is easier to distinguish the contents of the output and the client, the server's correspondence. It can also modify the program to provide more powerful features, or more satisfied with the reader.

8.3.9 Support multiple customers' 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.

The client program and the above program are exactly the same. If the reader reads the above program carefully, you can skip the unread, focus on the program of the main energy on the Server side.

1. Client program: MultitalkClient.java

2. Server-side program: MultitalkServer.java

3. Program ServerThread.java

1. Client program: MultitalkClient.java

Import java.io. *; import java.net. *; public class multitalkclient {public static void main (string args []) {Try {socket socket = new socket ("127.0.0.1", 4700); // port 4700 issued the client's requests BufferedReader sin = new BufferedReader (new InputStreamReader (System.in)); // input device is configured by the system standard BufferedReader objects PrintWriter os = new PrintWriter (socket.getOutputStream ()); // the Socket object to obtain an 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 () ; // Read a string from the system standard for a string while (! Readline.e ")) {// Stop cyclic OS.println (Readline) if the string read from the standard input is" BYE "; // Output the string read from the system standard to Server Os.Flush (); // Refresh the output stream so that Server will immediately receive the string system.out.println ("Client:" readline); / / Print read string system.out.println on the system standard output ("Server:" is.readline ()); // reads a string from Server and prints to the standard output Readline = 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} catch (Exception E) {system.out.println ("Error" E); // error, print error information}}}} 2. Server-side program: MultitalkServer.java

Import java.io. *; import java.net. *; import serverthread; public class multitalkserver {static int clientnum = 0; // static member variable, record the current customer's number of public static void main (String args []) THROWS IOException {ServerSocket serverSocket = null; boolean listening = true; try {serverSocket = new ServerSocket (4700); // Create a ServerSocket listening client on port 4700 requesting} catch (IOException e) {System.out.println ( "Could not listen On Port: 4700. "); // Error, print error message system.exit (-1); // exit} while (listening) {// Forever loop listen new ServerThread (ServerSocket.Accept (), clientnum) .start .start (); // to create a 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 (); // Turn serverSocket}} 3. Program ServerThread. Java

Import java.io. *; import java.net. *; public class serverthread extends thread {socket socket = null; // Save the socket object INT clientNum related to this thread; // 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 {String Line; BufferedReader IS = new BufferedReader (new InputStreamReader (socket.getInputStream ())); // Socket object obtained by the input stream, and the corresponding configuration of the object BufferedReader PrintWriter os = newPrintWriter (socket.getOutputStream ()); // get the object from the Socket stream output and configured PrintWriter object BufferedReader sin = new BufferedReader (new InputStreamReader (System.in)); // input device is configured by the system standard BufferedReader objects System.out.println ( "Client:" clientnum is.readLine ()); / / Print a string LINE = Sin.Readline () read from the client on the standard output; // read a string from the standard input while (! Line.equals ("BYE")) {// If The string is "BYE", then stop the loop OS.Println (line); / / output the string Os.Flush (); // refresh the output stream to the client, so that the client will receive the string system.out immediately. PRIN TLN ("Server:" line); // Print this string in system standard output System.Out.println ("Client:" ClientNum Is.Readline ()); // Read a string from Client And print it on the standard output on line = sin.readline (); // Read a string from the system standard input} // Continue loop 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 information}} This program shows the reader to the most typical C / S structure in the network application, we can describe such a model with the following graph:

Through the above learning, the reader should have a more comprehensive understanding of the Java's flow-on network programming, which is based on TCP applications, and we will introduce UDP-based Socket programming. 8.3.10 When the TCP / IP protocol is reported to the TCP / IP protocol, we have already mentioned that in addition to the TCP protocol, the TCP protocol has a UDP application, it is not as good as TCP. Wide, several standard application layer protocols HTTP, FTP, SMTP ... are 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:

TCP, reliable, transmission size is unlimited, but it is necessary to connect the establishment time, and the error control overhead is large. UDP, unreliable, error control overhead is small, the transmission size is limited to 64K, and no connection is required.

In summary, the two agreements have characteristics, the application is also different, and it is a fully complementary agreement that possesses the same important status in the TCP / IP protocol. To learn the network programming, the two are unable. 8.3.12 DataGram communication representation: DataGramsocket; DataGramSocket package Java.NET provides two class DataGramsocket and DataGRamPacket to support datagram, DataGramsocket is used to establish a communication connection to establish a transfer datagram between programs. DataGrampacket uses To represent a datam. 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);

Before sending data, you must be a new DataGrampacket object. At this time, you should use the second constructor above, while give a complete destination address, including an IP address. And port numbers. 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);

When constructing a dibaralization, an inetaddress class parameter is given. 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.13 Simple Client / Server Program Design Based on UDP

With the above knowledge, we can come to the component a UDP-based C / S network transmission model

Value program quoteclient.java

2. Server program: QuoteServer.java

3. Program quoteServerthread.java

Value program quoteclient.java

Import java.io. *; import java.net. *; import java.util. *; public class quoteclient {public static void main (string [] args) throws oews oews oException {if (args.length! = 1) {// If you don't give the name of the Server when started, then exit System.Out.println ("Usage: Java QuoteClient)

");

// Print an error message

Return; // Return

}

DataGramsocket Socket = new datagrament (); // Create a data settlement

Byte [] buf = new byte [256]; // Create a buffer inetaddress address = inetaddress.getbyName (args [0]); // The first parameter given by the command line defaults to the name of the Server, through it Server IP Information DataGrampacket Packet = New DataGrampacket (BUF, BUF.LENGTH, Address, 4445); // Create a DataGraMpacket Object Socket.send (Packet); // Send Packet = New DataGrampacket (buf, buf.length); // Create a new DataGrampacket object, used to receive datagram socket.Receive (Packet); // receive string received = new string (packet.getdata ()); // Generate the corresponding string system based on the received byte array. Out.println ("Quote of the Moment:" Received); // Print the generated string

Socket.close (); // Close socket}}

2. Server program: QuoteServer.java

Public class quoteserver {public static void main (string args []) throws java.ioException {new quoteServertHread (). start (); // Start a quoteSerVerthread thread}}

3. Program quoteServerthread.java

import java.io. *; import java.net *;. import java.util *;. // server threads public class QuoteServerThread extends Thread {protected DatagramSocket socket = null; DatagramSocket // objects of the present recording and associated objects protected BufferedReader IN = null; // A Reader Protected Boolean more morequotes = true; // flag variable is used to read the file, continue to operate

public QuoteServerThread () throws IOException {// this constructor with no arguments ( "QuoteServerThread"); // call to the default value QuoteServerThread parameters constructor} public QuoteServerThread (String name) throws IOException {super (name); / / Call the constructor of the parent class socket = new datagramsocket (4445); // Create a data settlement in port 4445 Try {IN = New BufferedReader (New FileReader ("One-LineReader)); // Open one File, construct the corresponding BufferReader object} catch (filenotfoundexception e) {// exception handler system.err.println ("Could Not open quote file. Serving time instead."); // Print error information}} public void Run () // Thread main body {while (morequotes) {Try {byte [] buf = new byte [256]; // Create buffer DataGrampacket packet = new data, buf.length); // constructed by buffer DataGrampacket object Socket .Receive (Packet); // Receive Datashers String DString = NULL; if (in = = null) DSTRING = New Date (). TOSTRING (); // If the initialization is opened, open the file failed, // Use the date As the string else dstring = getNextQuote (); / / otherwise call the member function to read the string buf = dstring.getbyte (); // Convert String By the byte array to transfer inetaddress address = packet.getaddress (); // Get a client address INT port = packet.get port number from the Packet from the Client end (); // and port number packet = new DataGrampacket (buf, BUF.LENGTH, Address, Port); // Build a DataGrampacket Socket.send (Packet) according to client information; // Send Data News} Catch (IOEXCEPTION E) {// Abnormal Processing E.PrintStackTrace (); // Print Error Stack morequotes = false; // logo variable set FALSE to end cyclic}} Socket.close (); // Turn off Data Supply Settings}

Protected string getnextQuotes () {// member function, read data from the file String ReturnValue = null; try {ix ((returnvalue = in.readline ()) = = null) {// read a line from the file, if you read File tail in.close (); // Close input stream morequotes = false; // flag variable set FALSE to end cyclic returnvalue = "no more quotes. Goodbye."; // Set return value} // Otherwise return string That is, the string read from the file} catch (IECEPTION E) {// Exception ReturnValue = "IOEXCEPTION OCCURRED IN Server"; // Set an exception return value} return returnvalue; // Return string}} can be seen UDP and use TCP still have a big difference on the program. A more obvious difference is that UDP's Socket programming is not to provide monitoring function, that is, communication between communication is more equal and facing interfaces are exactly the same. However, in order to implement a C / S structure with UDP, you can use DataGramsocket.Receive () when using UDP to implement a function similar to listening. Because Receive () is a blocking function, when it returns, the buffer has been filled with a datagram, and can obtain various information of the sender from the data, this point is very good at Accept () is very As an example, it can determine the next action based on the read datagram, which has achieved similar effects with the network. 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.

We make some modifications to the above procedures, and broadcast communication with MulticastSocket. The function of the new program is to make the plurality of client programs running simultaneously to receive the same information as the server sent, displayed on their respective screens.

1. Client program: multicastclient.java

2. Server program: Multicast Server.java

3. Program MulticastServertHread.java

1. Client 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 4446 port broadcast socket inetaddress address = inetaddress.getbyname ("230.0.0.1"); // Get address information of 230.0.0.1 SOCKET.JOINGROUP (Address); // Use joingroup () Bind broadcast socket DecraMpacket packet on the address;

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 (); // Turn off broadcast socket}} 2. Server program: MulticastServer.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 // inherited from the server to get a new QuoteServerThread thread class MulticastServerThread {Private long FIVE_SECOND = 5000; // define constants, 5 seconds PUBLIC MULTICASTSERVERTHREAD (STRING NAME) THROWS IEXCEPTION {Super ("MulticastServertHread"); // Call the parent class, that is, the constructor of QuoteServerthread}

Public void run () // Rewriting the thread main body of the parent class {// Depending on the logo variable determines whether to continue loop 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 fails, the date is used as the string else dstring = getNextQuote (); / / Otherwise call the member function to read the string buf = dstring.getbyte () in the file, convert the string into byte arrays to transfer send it inetaddress group = inetaddress.getbyname ("230.0.0.1"); // Get the address information of 230.0.0.1 DataGrampacket Packet = New DataGrampacket (Buf, Buf.length, Group, 4446); // Create a DataGrampacket object Socket.send (Packet) according to buffer, broadcast address, and port number; // Send Packet try {sleep_seconds); // Random Wait for a period of time, 0 ~ 5 seconds} Catch (InterruptedException E) {} // Abnormal Processing} Catch (IOException E) {// abnormal processing E.PrintStackTrace (); // Print error stack morequotes = false; // set end cycle flag}} Socket.close (); // Turn off broadcast socket}}

At this point, the chapter of Java Network Programming has been explained. The readers should have a clear understanding of the network programming, which may not be very clear about some concepts, or need more practices to further master. The learning language learning is different from general learning, and its emphasizes the importance of practice. Readers should make a lot of TCP in the URL network programming, and the TCP programming in Socket will make a lot of practice to better master some of the concepts mentioned in this chapter can truly learn the essence of Java network programming!

In the last few sections, the reader is necessary to experiment, if you encounter problems, you want to solve it. It is best to improve it according to your intentions. This will better understand these procedures and understand the programming ideas included. [本 讲 小]

This lecture mainly explains network programming in the Java environment. Because the TCP / IP protocol is the basics of Java network programming, this statement focuses on some concepts in the TCP / IP protocol. The TCP / IP protocol itself is a very large system, and it is impossible to use several sub-sections. . 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, a piece is a URL as the main line, explaining how to access the WWW network resources through the URL class and the URLConnection class, because the URL is very convenient, although the function is not strong, it is worth recommending a network programming Methods, especially for beginners, particularly easy to accept. Essentially, the URL network programming or the TCP protocol used in the transport layer. Another piece is the main line with the Socket interface and the C / S network programming model, in turn explain how to implement TCP-based C / S structure with Java, which is mainly used with Socket, Serversocket. And how to use Java-based C / S structure, and discuss a special transmission method, broadcast mode, this approach is unique to UDP, mainly used in DataGramsocket, DataGrampacket, MulticastSocket. This piece is relatively difficult in Java network programming (although Java has made "fool" in this area, network programming is a very headache, and then "" Fool "still has a certain difficulty), is also the most powerful part of the function, readers should study and understand the ideas.

Finally, it is necessary to study Java network programming, Java language, most important thing is to practice!

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

New Post(0)