Java Socket Information

xiaoxiao2021-03-06  32

In fact, the NET's Socket test is very low. Basically, it is basically aware of these Socket exams that can be paid to network workers. By the way, an affected exam is impossible to change the test. The content, so I personally think that the network should still take Java's socket in the future.

Java socket programming (on) Using Java development network software is very convenient and powerful, this power of Java comes from his unique set of powerful APIs, these APIs are a series of classes and interfaces. Located in the package java.net and javax.net. In this article, we will introduce the sockets, while explaining how to use the NetWork API manipulator, after completing this article, you can write low-end communications software.

What is a socket?

The Network API is a typical TCP / IP network Java program to communicate with other program communication, and the Network API relies on Socket for communication. Socket can be seen as one endpoint in the communication connection in the two programs, and a program writes a piece of information into the Socket, which sends this information to another Socket so that this information can be transmitted to other programs.

Let's analyze the program A on Host A to write a message into socket, and the content of Socket is accessed by Host A network management software, and this information is sent to Host B, Host B After receiving this information, the network interface card is transmitted to the network management software of Host B, and the network management software saves this information in the Host B Socket, and then the program B can read this information in the socket.

Suppose the third host Host C is added to the network of Figure 1, then how does Host A know that the information is transmitted correctly to Host B instead of being transferred to Host C? Each host based on the TCP / IP network is given a unique IP address. The IP address is a 32-bit unsigned integer. Since it is not converted to binary, it is usually separated by a decimal point, such as: 198.163.227.6, just as The IP addresses are all consisting of four parts, each of which is 0-255 to represent an 8-bit address.

It is worth noting that the IP address is 32-bit address. This is the IP Protocol version 4 (IPv4) specified. Currently since IPv4 addresses are nearly exhausted, IPv6 addresses are gradually replacing IPv4 addresses. The IPv6 address is 128 Symbol integer.

Suppose the second program is added to Host B of the network of Figure 1, then how can the information from Host A can be correctly transmitted to program b instead of passing to newly joined programs? This is because each TCP / IP network communication program is given a unique port and port number. The port is an information buffer for retaining the input / output information in the socket. The port number is a 16-bit unsigned symbol. Integer, the range is 0-65535 to distinguish every program on the host (port number is like a room number in the house), the short slogan below 256 is reserved to the standard application, such as the port number of POP3 is 110, each The sockets are combined into the IP address, port, port number, which can distinguish every socket T, let's talk about two sockets: Flow socket and self-address data Socket.

Stream socket

Whenever, when sending and receiving information between two network applications, a reliable connection is required, and the flow cover is relying on the TCP protocol to ensure that the information is properly reached. In fact, the IP package may be in the network. Lost or errors during the transfer, any case occurs, and the TCP, which is the acceptor, resensively, re-sends this IP package. This is the so-called establishing a reliable connection between two flow sockets. Flow socket plays a necessary role in the C / S program, the client program (the network application that needs to access some services) creates an IP address and server program for hosting the server's host (provided for client applications) The port number of the port number of the service network application.

The initialization code of the client-end socket passes the IP address and port number to the network management software of the client host, and the management software passes the IP address and port number to the server host by NIC; the server-side host reads the NIC transmission Data, then check if the server program is in the listening state, which is still performed by a socket and port; if the server program is listening, the server-side network management software issues a positive After receiving the response signal, the client flow sleeve initialization code creates a port number to the client program, and passes the port number to the server program (the server program will use this port number to identify Whether the information belongs to a client program) At the same time, the initialization of the stream sleeve is completed.

If the server program is not in the listening state, the server-side network management software will pass a negative signal to the client. After receiving this negative signal, the client's flow sleeve initialization code will throw an exception object and do not establish a communication connection. Nor creating a streamlined temple object. This situation is like calling, when someone is established, otherwise the phone will hang.

This part of the work includes three classes of associated: Inetaddress, Socket, and Serversocket. The inetaddress object depicts a 32-bit or 128-bit IP address. The Socket object represents the client's junction. ServerSocket represents the service roller socket, all of which are located in the package java.net.

Inetaddress class

The inetaddress class plays an important role in the network API socket programming. Parameters pass to the flow sleeve and self-add-in socket class constructors or non-constructor methods. Inetaddress describes 32-bit or 64-bit IP addresses. To complete this feature, the iNetAddress class mainly relys on two support class INet4address and inet6address, which is inheritance relationship, inetdrress is a parent class, Inet4address and inet6address are subclasses.

Since only one constructor is only a constructor, but cannot pass parameters, it is not possible to create an inetaddress object, such as the following practices are wrong: inetaddress = new inetdress (); but we can create one by the following five factory methods Inetaddress object or inetaddress array:

GetAllByname (String Host) method Returns a reference to an inetadDress object, each object contains a separate IP address that represents the corresponding hostname, this IP address is passed through the Host parameter, and if there is no IP address for the specified host, if there is no IP address Method will throw a unknownhostException exception object.

GetByAddress method Returns a reference to an inetaddress object, which contains an IPv4 address or IPv6 address. The IPv4 address is a 4-byte array. The IPv6 address is a 16-byte address array, if returned Nothing is neither 4 bytes, then the method will throw a unknownhostException exception object. GetByaddress (String Host, Byte [] addr method Returns a reference to an inetaddress object, which contains an IP address specified by the Host and 4 bytes of AddR array, or Host and 16-byte ADDR array specified The IP address, if this array is neither 4 bytes nor 16-bit bytes, then this method will throw a unknownhostException exception object.

. getByname (String Host) method Returns an inetaddress object that contains an IP address corresponding to the host specified by the Host parameter. For the specified host, if there is no IP address exists, then the method will throw a unknownhostException exception object.

The getLocalHost () method returns an inetaddress object, which contains the IP address of the local machine. Considering that the local host is both a client host and a server host, in order to avoid confusion, we call the client host as a customer host, put the server The program host is called a server host.

Both of the methods mentioned above refer to a reference to returning one or more inetaddress objects. In fact, each method returns a reference to one or more Inet4address / inet6address objects, and the caller does not need to know the subtypes referenced, the opposite caller The non-static method of the inetaddress object can be invoked using the returned reference, including the polymorphism of the subtype to ensure that the overload method is called.

Inetaddress and its subtype object handle the transformation of the host name to the host IPv4 or IPv6 address. To complete this conversion, you need to use a domain name system. The following code demonstrates how to get the getByname method to get an inetaddress sub-class object, This object contains IP addresses corresponding to the Host parameter: inetaddress = inetaddress.getbyname (www.javajeff.com);

Once the reference to the inetaddress sub-object, you can call the INetAddress's various ways to get IP address information in the inetaddress subclass object, for example, you can get standard host names from domain name services by calling getcanonicalhostname (); gethostaddress ) Get the IP address, getHostName () get the host name, isloopBackAddress () determines if the IP address is a loopback address.

List1 is a demonstration code: inetaddressdemo // inetaddressDemo.java

Import java.net. *;

Class inetaddressdemo {public static void main (string [] args) throws unknownhostexception {string host = "localhost";

IF (args.length == 1) Host = args [0];

Inetaddress = inetaddress.getbyname (Host);

System.out.println ("canonical host name =" Ia.getcanonicalHostName ()); System.out.Println ("Host Address =" Ia.GethOstaddress ()); System.out.Println ("Host Name =" Ia.getHostName ()); System.out.Println ("is loopback address =" };}} When there is no command line parameter, the code output is similar to the following results: Canonical Host Name = localhosthost Address = 127.0.0.1Host Name = localhostis loopback address = TRUE

InetaddressDemo gave you a choice for a specified host name as a command line parameter. If there is no host name being specified, use localhost (client), INetaddressDemo get a reference to the getByName (String Host) method, The standard host name, host address, host name, and IP address are the output of the LoopBack address by this reference.

Socket class

When the client needs to communicate with the server program, the client program creates a socket object in the client, and the Socket class has several constructor. Two commonly used constructors are socket (Inetaddress Addr, INT port), and socket (String Host, INT port), two constructor created a streamlined text of Socket-based connection server-side stream jacket. For the first inetaddress subclass object, the IP address of the server host is obtained through the ADDR parameter. For the second function Host parameter package is assigned to the inetaddress object, if there is no IP address consistent with the Host parameter, then the unknownhostexception exception object will be thrown . Both functions get the port number of the server through the parameter port. Assume that the connection has been established, the network API will bundle the IP address and any port number of the client based on the socket-based stream socket, otherwise the two functions will throw an IOException object.

If a socket object is created, it may obtain the information transmitted from the service program by calling the GetInputStream () method of the socket, or the output stream can also be sent by calling the getoutputstream () method to call the socket. After the read and write activity is completed, the client program calls the close () method to close the flow and streamlined connections. The following code creates a service host address of 198.163.227.6, port number 13 Socket object, and then created from this new creation The input stream is read in the Socket object, and then turn off the stream and socket objects. Socket S = New Socket ("198.163.227.6", 13); InputStream IS = S.GetinputStream (); // read from the stream.isclose (); s.close ();

Next, we will demonstrate a jacket reader, this program will create a socket object, and the socket will access the service program running on the specified host port 1000. If the access success client will send a series of commands to the service program and The response of the print service program. List2 enables us to create programs SSClient's source code: Listing 2: ssclient.java// ssclient.java

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

Class ssclient {public static void main (String "args) {string host =" localhost ";

// if User Specifies A Command-Line Argument, That Argument // Repesents The Host Name.

IF (args.length == 1) Host = args [0];

BufferedReader Br = NULL; PrintWriter PW = NULL; SOCKET S = NULL;

Try {// Create a socket That Attempts to Connect To The Server // Program on The Host At Port 10000.

s = new socket (Host, 10000);

// Create an input stream reader that chains to the socket's // byte-oriented input stream. The input stream reader // converts bytes read from the socket to characters. The // conversion is based on the platform's default character // set.

InputStreamReader ISR; ISR = New InputStreamReader (S.GetinputStream ());

..

Br = New BufferedReader (ISR);

// Create a print writer that chains to the socket's // oriented output stream byte-. The print writer creates an // intermediate output stream writer that converts // characters sent to the socket to bytes. The conversion // is based on the Platform's Default Character Set.

PW = New PrintWriter (s.getoutputstream (), true);

// send the date command to the server.

PW.Println ("Date");

// Obtain and print the current date / time.

System.out.println (Br.Readline ()); // send The Pause Command to the Server. This allows several //clients to start and verifies That the Server is spawning // multiple threads.pw.println ("Pause" // send the down command to the server.

PW.Println ("Dow");

// Obtain and print The Current Day of WEEK.

System.out.println (br.ready ());

// send the dom command to the server. Pw.println ("DOM");

// Obtain and print the current day of month.

System.out.println (br.ready ());

// dend the doy command to the server.

PW.Println ("DOY");

// Obtain and print the current day of year.

System.out.println (br.readline ());} catch (ioException e) {system.out.println (e.tostring ());} finally {try {if (br! = Null) br.close () ;

IF (pw! = null) PW.Close ();

IF (s! = null) s.close ();} catch ({oException e) {}}}} Running this program will get the following results: Tue Jan 29 18:11:51 CST 2002tuesday2929

SSCLIT creates a socket object to contact the service program running on the host port 10000, and the IP address of the host is determined by the Host variable. SSCLIENT will get the input and output flow of the Socket, which is very easy to read and write the string with the input stream of the bufferedReader and the output stream of the PrintWriter. The SSCLIENT Server issues a variety of DATE / TIME commands and responds, each response All are printed, once the last response is printed, the FinalLe Schiter string of the Try / Catch / Finally structure will be executed, and the Finally substring will close the bufferedReader and PrintWriter before closing the socket.

Once the SSCLIENT source code is completed, you can enter Java SSClient to perform this program. If there is a suitable program running on a different host, use the hostname / IP address as the input method of the parameter, such as www.sina.com.cn It is the host running the server program, then the input method is java ssclient www.sina.com.cn.

skill

The Socket class contains many useful methods. For example, getLocaladdress () will return a reference to the inetaddress subclass object containing the client IP address; getLocalPort () will return the port number of the client; getinetaddress () will return a reference to the inetaddress subclass object containing the server IP address; getPort () Will return the port number of the service program.

Serversocket class

Since SSCLIT uses a stream sleeve, the service program also uses a stream socket. This is to create a serversocket object, serversocket has several constructor, the simplest ServerSocket (INT Port), when you create a ServerSocket object, the port parameter passes the port number, this port is the server listening connection request Port, if an error will throw an IOEXception exception object, otherwise the ServerSocket object will be created and ready to receive the connection request. Next, the service program enters an infinite loop, and the unlimited loop begins with the accept () method of calling ServerSocket, and the accept () method will cause the call to block until the connection is created. After establishing the connection, Accept () returns a recently created Socket object, the socket object binds the client's IP address or port number.

Since there is a single service program with multiple client program communication, the service program responds to the client should not spend a lot of time, otherwise the client program will spend a lot of time before getting the service, but the service procedure and client program The session may be very long (this is similar to the phone), so the typical way to speed up the request for the client program, the typical method is that the server host runs a background thread, the backend threading processor and the client program.

In order to demonstrate that we are talking about and complete the SSCLIENT program, let's create a SSServer program, the program will create a ServerSocket object to listen to the port 1000 connection request, if the successful service program will wait for the connection, start a thread processing connection And responsive to commands from the client. Here is the code of this program:

Listing 3: SSSERVER.JAVA // SSSERVER.JAVA

Import java.io. *; import java.ut. *; import java.util. *;

Class ssserver {public static void main (string [] args) throws iodception {system.out.println ("Server Starting ... / N");

// Create a Server Socket That Listens for Incoming Connection // Requests on Port 10000.

Serversocket Server = New ServerSocket (10000);

While (True) {// listen for incoming connection requests from client // Program, Establish a connection, and return a socket // Object That Reresents this connection.

Socket S = Server.Accept ();

System.out.println ("Accepting Connection ... / N");

// Start a thread to handle the connection.

New ServerThread (s) .start ();}}}

Class ServerThread Extends Thread {Private Socket S;

ServerthRead (socket s) {this.s = s;}

public void run () {BufferedReader br = null; PrintWriter pw = null; try {// Create an input stream reader that chains to the socket's // byte-oriented input stream The input stream reader // converts bytes read from the socket. TO Characters. The // Conversion is based on the placeform's default character // set.

InputStreamReader ISR; ISR = New InputStreamReader (S.GetinputStream ());

..

Br = New BufferedReader (ISR);

// Create a print writer that chains to the socket's // oriented output stream byte-. The print writer creates an // intermediate output stream writer that converts // characters sent to the socket to bytes. The conversion // is based on the Platform's Default Character Set.

PW = New PrintWriter (s.getoutputstream (), true);

// Create a Calendar That Makes It Possible To Obtain Date // And Time Information.

Calendar c = calendar.getInstance ();

// Because the client program may send multiple commands, a // loop is required. Keep looping until the client either // explicitly requests termination by sending a command // beginning with letters BYE or implicitly requests // termination by closing its output stream .

Do {// Obtain The Client Program's next command.

String cmd = br.readline ();

// EXIT IF Client Program Has Closed Its Output Stream.

IF (cmd == null) Break; // Convert Command to Uppercase, for Ease of Comparison.

CMD = cmd.touppercase ();

// if Client Program Sends Bye Command, Terminate.

IF (cmd.startswith ("BYE")) Break; // if Client Program Sends Date Or Time Command, Return // Current Date / Time To The Client Program.

IF (cmd.startswith ("date") || cmd.startswith ("time")) PW.Println (C.getTime () .tostring ());

// if Client Program Sends Dom (Day of Month) Command, // Return Current Day of Month To The Client Program.

IF (cmd.startswith ("DOM"))) PW.Println ("" C.Get (Calendar.day_of_month);

// if Client Program Sends Dow (Day of Week) Command, // Return Current Weekday (as a string) To the client // program.

IF (cmd.startswith ("DOW"))) Switch (CASE CALENDAR.SUNDAY: PW.PRINTLN ("sunday"); Break;

Case Calendar.monday: PW.Println ("Monday"); Break;

Case Calendar.tuesday: PW.Println ("Tuesday"); Break;

Case Calendar.wednesday: PW.Println ("Wednesday"); Break;

Case Calendar.thursday: PW.Println ("Thursday"); Break;

Case Calendar.friday: PW.Println ("Friday"); Break;

Case Calendar.SAturday: PW.Println ("Saturday");

// if Client Program Sends Doy (Day of Year) Command, // Return Current Day of Year To The Client Program.

IF (cmd.startswith ("DOY"))) PW.Println ("" C.Get (Calendar.day_of_year);

// if Client Program Sends Pause Command, Sleep for Three // Seconds. IF (cmd.startswith ("pause")) Try {thread.sleep (3000);} catch (interruptedException e) {}}. {Catch (ioException e) {system.out.println (e.tostring ());} finally {system.out.println ("Closing Connection ... / N"); try {if (br! = Null) BR .Close ();

IF (pw! = null) PW.Close ();

IF (s! = null) s.close ();} catch (ooException e) {}}}} Running this program will get the following output:

Server Starting ... Accepting Connection ... Closing Connection ... SSServer source code declares a pair of classes: SSSERVER and ServerThread; SSServer's main () method creates a ServerSocket object to listen to the connection request on the port 1000, if Successfully, SSServer enters an infinite loop to alternately call the Accept () method of ServerSocket to wait for the connection request, and start the request for the background threading process (Accept () returned). The thread starts from the START () method inherited by ServerThread, and executes the code in the RUN () method of ServerThread.

Once the run () method is running, the thread will create bufferedReader, PrintWriter, and Calendar objects and enter a loop, this loop is started by reading (by bufferedreader's readline ()) from the client, the text (command) is stored in the CMD reference In the String object, what happens if the customer program is too early to turn off the output flow? The answer is: CMD will not be assigned.

Note that this must be taken into account: When the service program is in the input stream, the client is turned off the output stream, and if this situation is not handled, the program will produce an exception.

Once the SSServer source code is compiled, run the program by entering Java SSServer, and after starting SSSERVER, you can run one or more SSCLIENT programs.

Self-address socket (DataGram Sockets)

Because each connection of the flow sleeve is taken for a certain amount of time, to reduce this overhead, the network API provides a second socket: self-address socket, self-addressed UDP sends addressing information (from the customer program to the service program or from the service program to the client program), the difference is that the multi-IP packet can be sent by the self-address socket, and the self-addressed information is included in the self-address package. In addition, the self-address package is also included in the IP packet, which limits the address length within 60000 bytes. Figure 2 shows the self-addressing information of the self-address package in the IP package. Unlike TCP to ensure that the information destined in the information destination is different. UDP provides another method. If the self-addressed packet does not reach the destination, then UDP will not request the sender to resend the self-address package, because UDP contains error detection information in each self-address package. After each self-address package reaches the destination, only simple error checks, if the detection failed, the UDP will abandon this self-adding package, nor Request from the sender, this is similar to that the letter sent by the post office, the sender does not need to connect to the recipient before sending the letter, and the letter can not be guaranteed to arrive at the recipient to the self-address socket work including the following Three categories: DataGrampacket, DataGramsocket, and MulticastSocket. The DataGrampacket object depicts the address information of the self-address package. NET package.

DataGrampacket class

Before using the self-address package, you need to first familiarize the DataGrampacket class, address information, and self-address packages simultaneously in the manner of byte an array simultaneously into this class.

DataGrampacket has several constructor, even if these constructor is different, but usually they have two common parameters: BYTE [] Buffer and int LENGTH, the buffer parameter contains a word that saves the self-addressed packet information The reference is referenced by the array, and the length indicates the length of the byte array.

The simplest constructor is DataGrampacket (Byte [] Buffer, INT Length), which determines the length of the number of self-addressed packets and arguments, but there is no address and port information of the data packet, which can be The following code demonstrates these functions and methods by calling Method Setaddress (INETADDRESS ADDR) and SETPORT (INT Port). Byte [] buffer = new byte [100]; DataGrampacket DGP = New DataGrampacket (Buffer, Buffer.Length); inetaddress IA = inetaddress.getbyName ("www.disney.com"); DGP.Setaddress (IA); DGP.SETPORT (6000); // Send DataGram Packet To Port 6000.

If you prefer to include the address and port number while calling the constructor, you can use the DataGrampacket function, the following code demonstrates another option.

Byte [] buffer = new byte [100]; inetaddress IA = inetaddress.getbyname ("www.disney.com"); DataGrampacket DGP = New DataGrampacket (Buffer, Buffer.Length, IA, 6000); Sometimes created DataGrampacket After the object wants to change the byte array and his length, it can be implemented by calling setData (Byte [] Buffer) and setLength method. At any time, you can get a reference to the byte array by calling getData () to get the length of the byte array by calling getLength (). The following code demonstrates these methods:

Byte [] buffer2 = new byte [256]; DGP.SetData (Buffer2); DGP.SetLength;

For more information on DataGrampacket, please refer to the SDK documentation. DataGramsocket class

The DataGramsocket class creates a self-address socket in the client to communicate with the server side, and send and receive self-add-in socket. Although there are multiple constructors to choose from, I found that the most convenient choice for creating client self-address sockets is a DataGramsocket () function, and the server side is a DataGramsocket function, if it is not created Sack socket or bound self-adder socket to local port, then these two functions will throw a socketException object, once the program creates a DataGramsocket object, then the program calls Send (DataGrampacket DGP) and Receive (DataGrampacket) DGP) to send and receive self-addressed packets,

The DGSClient source code displayed by List4 demonstrates how to create a self-addressing socket and how to send and receive information through a socket.

Listing 4: dgsclient.java// DgsClient.java

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

Class DgsClient {public static void main (string "args) {string host =" localhost ";

// if User specifies a command-line argument, That argument // represents the host name. If (args.length == 1) host = args [0];

DataGramsocket S = NULL;

Try {// Create a DataGram Socket Bound to an Arbitrary Port.

S = new DataGramsocket ();

// Create a byte array that will hold the data portion of a // datagram packet's message. That message originates as a // String object, which gets converted to a sequence of // bytes when String's getBytes () method is called. The // Conversion Uses The Platform's Default Character Set.

BYTE [] Buffer; Buffer = New String ("Send Me A Datagram"). GetBytes (); // Convert the name of the host to an inetaddress object. // That Object Contains the ip address of the host and is // Used by DataGrampacket.

Inetaddress = inetaddress.getbyname (Host);

// Create a DatagramPacket object that encapsulates a // reference to the byte array and destination address // information The destination address consists of the // host's IP address (as stored in the InetAddress object) // and port number 10000. - The Port On Which The Server // Program Listens.

DataGrampacket DGP = New DataGrampacket (Buffer, Buffer.Length, IA, 10000);

// dend the datagram packet over the socket.

S.send (DGP);

// Create a byte array to hold the response from the server. // program.

Byte [] buffer2 = new byte [100];

// Create a DataGrampacket Object That Specifies A Buffer // To Hold The Server Program's response, The IP address of // The Server Program's Computer, And Port Number 10000.

DGP = New DataGrampacket (Buffer2, Buffer.length, IA, 10000);

// Receive A DataGram Packet over the socket.

S.Receive (DGP);

// Print The Data Returned from The Server Program and Stored // In The DataGram Packet.

System.out.println (New String (DGP.GetData ()));

} Catch (ioException e) {system.out.println (e.tostring ());} finally {if (s! = Null) s.close ();}}}

DGSCLIENT starts with a DataGramsocket object that is binding any local (client) port, then loads an array buffer with text information and a reference to the inetaddress subclass object of the server host IP address, next, DgsClient creates one DataGrampacket object, the object adds a reference to the buffer with text information, reference to the inetaddress subclass object, and the service port number 10000, the self-adding data packet of the DataGrampacket is sent to the server program, which contains services. The new DataGrampacket object of the program response is created, received () get the response self-adder packet, then the getData () method of the addressing packet returns a reference to the self-addressed packet, and finally closes the DataGramsocket. The DGSServer service program has complementing the shortcoming of DGSClient, and List5 is the source code of DGSServer:

Listing 5: DGSServer.java// DGSServer.java

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

Class DGSServer {public static void main (string [] args) throws oews oException {system.out.println ("Server Starting ... / N");

// Create a DataGram Socket Bound To Port 10000. DataGram // Packets Sent From Clom Clom Programs Arrive At this Port.

DataGramsocket S = New DataGramsocket (10000);

// Create a Byte Array to Hold Data Contents of Datagram // Packet.

BYTE [] DATA = New byte [100];

// Create a DatagramPacket object that encapsulates a reference // to the byte array and destination address information. The // DatagramPacket object is not initialized to an address // because it obtains that address from the client program.

DataGrampacket DGP = New DataGrampacket (Data, Data.Length);

// Enter an infinite loop. Press Ctrl C to Terminate Program.

While (True) {// receive a DataGram Packet from the client program.

S.Receive (DGP);

// Display Contents of DataGram Packet.

System.out.println (New String (DATA));

// Echo DataGram Packet Back to Client Program.

S.send (DGP);}}}

DGSServer creates a self-address socket of a binding port 1000, then creates a byte array to accommodate the self-addressing information, and create a self-adder package, next, DGSServer enters an infinite loop to receive self-address data Package, display the content and return the response to the client, and the self-addressing sleeve is not closed because the loop is unlimited. After compiling DGSServer and DgsClient, starting DGSServer by entering Java DGSServer, then entering Java DGSClient on the same host, if DGSServer is running on different hosts, pay attention to the command line when you enter The host name or IP address of the program, such as Java DgsClient www.yesky.com

Multi-point transfer and multicastsocket class

The previous example shows that the server program thread sends a single message (through the flow socket or self-address socket) to the only client program, this behavior is called a single point transfer, most of the cases Suitable for single-point transmission, for example, rock singer will play a concert will play through the Internet, the quality of the screen and sound depends on the transmission speed, the server program is to transmit approximately 1 billion bytes of data to the client program, using single point Transfer, then each client must copy a data, if you have 10,000 clients on the Internet, you need to watch this concert, then the server program transmits 10000g of data over the Internet, which must cause the network to block, reduce the network. transfer speed.

If the server program wants to send the same information to multiple clients, the server program and the client can communicate multi-point transfer (multicasting). Multi-point transmission is a series of self-addressed data packets to serve the IP address and port of a dedicated multi-point transfer group. By joining the IP address by adding the IP address, you can receive a multi-point SOCKET. Self-address pack (same customer program can also send self-addressed packages to this group), once the client reads all the self-add-up packets to be read, you can leave the multi-point transfer group by leaving the group.

Note: IP addresses 224.0.0.1 to 239.255.255.255 (including) are all retained multi-point address.

The network API supports multi-point transfer through the MulticastSocket class and MulticastSocket, and some auxiliary classes (such as NetworkInterface), create a multicastSocket object when a client is to join a multi-point transmission group. MulticastSocket (int port) constructor allows the application to specify port (via port parameter) to receive self-address packs, port must match the port number of the service program, join multi-point transfer group, customer program call two joingroup () methods One of them, it is also necessary to leave the transfer group, but also to call one of the two LeaveGroup () methods.

Since MulticastSocket extends the DataGramsocket class, a MulticastSocket object has the right to access the DataGramsocket method.

List6 is the source code of McClient. This code demonstrates an example of a client to join a multi-point transfer group.

Listing 6: McClient.java// McClient.java

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

class MCClient {public static void main (String [] args) throws IOException {// Create a MulticastSocket bound to local port 10000. All // multicast packets from the server program are received // on that port.MulticastSocket s = new MulticastSocket ( 10000);

// Obtain An inetaddress Object That Contains The Multicast // Group Address 231.0.0.1. The inetaddress object is buy by // DataGrampacket.

Inetaddress group = inetaddress.getbyname ("231.0.0.1");

// Join The Multicast Group So That DataGram Packets Can Be // Received.

s.joingroup (group);

// Read Several DataGram Packets from The Server Program.

For (int i = 0; i <10; i ) {// no line will exceed 256 bytes.

Byte [] buffer = new byte [256];

// The DataGrampacket Object Needs No Addressing // Information Because The Socket Contains The Address.

DataGrampacket DGP = New DataGrampacket (Buffer, Buffer.Length);

// Receive a datagram packet.

S.Receive (DGP);

// Create a second byte arrayid.

BYTE [] Buffer2 = New Byte [DGP.GetLength ()];

// Copy The Sent Data to the second byte array.

System.Arraycopy (DGP.GetData (), 0, Buffer2, 0, Dgp.getLength ());

// print the contents of the second byte array. (Try // Printing the contents of buffer. You will soon see why // buffer2 is buy.)

System.out.println (New String (Buffer2));

// Leave the multicast group.

S.LeaveGroup (group);

// Close the socket.

s.close ();}}

McClient created a multicastSocket object that bind port number 10000, which is next to a inetaddress subclass object, which contains a multi-point transfer group's IP address 231.0.0, and then add more through JoingRoup (inetaddress addr) In the transfer group, then McClient receives 10 self-addresses, and outputs their content, then use the LeaveGroup (inetaddress addr) to leave the transfer group, and finally closing the socket. Maybe you feel strange to use two byte arrays buffer and buffer2, after receiving a self-address package, getData () method returns a reference, the length of the self-address package is 256 bytes, and if all data is to be output There will be many spaces after outputting actual data, which is obviously unreasonable, so we must remove these spaces, so we create a small byte array buffer2, buffer2's actual length is the actual length of the data, by calling DataGrampacket's The GetLength () method is to get this length. The method of quickly replicating the length to Buffer2 is called the System.ArrayCopy () method. The source code of List7 McServer shows how the service program works.

Listing 7: mcserver.java// mcserver.java

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

Class McServer {public static void main (string [] args) throws oews iodception {system.out.println ("Server Starting ... / N");

// Create a Multicastsocket Not Bound to any port.

MulticastSocket S = New MulticastSocket ();

// Because MulticastSocket Subclasses DataGramsocket, IT IS // Legal To Replace MulticastSocket S = New MulticastSocket (); // with the following line.

Document.write (""); // DataGramsocket S = New DataGramsocket ();

// Obtain An inetaddress Object That Contains The Multicast // Group Address 231.0.0.1. The inetaddress object is buy by // DataGrampacket.

Inetaddress group = inetaddress.getbyname ("231.0.0.1");

// Create a DatagramPacket object that encapsulates a reference // to a byte array (later) and destination address // information. The destination address consists of the // multicast group address (as stored in the InetAddress object) // and port number 10000 - the port to which multicast datagram // packets are sent (Note: The dummy array is used to prevent a // NullPointerException object being thrown from the // DatagramPacket constructor.) byte [] dummy = new byte [0]. ;

DataGrampacket DGP = New DataGrampacket (Dummy, 0, Group, 10000);

// send 30000 strings to the port.

For (int i = 0; i <30000; i ) {// create an array of bytes from a string. The Platform's // default version of the place // character // character // Characters to Bytes.

Byte [] buffer = ("Video Line" i) .getbytes ();

// establish the byte array as the datagram packet'S // buffer.

DGP.SETDATA (BUFFER);

// establish the byte array's length as the length of the // DataGram Packet's buffer.

DGP.setLength (Buffer.Length);

// send The DataGram to All members of the multicast group // That Listen on Port 10000.

S.send (DGP);

// Close the socket.

s.close ();}}

McServer created a MulticastSocket object, because he is part of the DataGrampacket object, so he does not bind port numbers, DataGrampacket has a multi-point IP address (231.0.0.0), once created a DataGrampacket object, McServer enters a transmission of 30,000 In the loop of the text, you have to create a byte array for each line of the text, and their references are stored in the previously created DataGrampacket object, and the self-address package is sent to all group members through the Send () method.

After compiling McServer and McClient, run McServer by entering Java McServer, running one or more McClient.

in conclusion

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

New Post(0)