Self-address sockets, because each connection of the use of flow sleeve is spent for a certain amount of time, to reduce this overhead, the network API provides the second socket: self-addressed socket DataGram Socket, self-addressed use UDP to send addressing information (from the customer program to the service program or from the service program to the customer program), the difference is that you can send multiple IP packets by self-address sockets, self-seeking The address information is included in the self-address package, and the self-adder 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 the sending letter through 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.
Self-addressing sockets include the following three classes: 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.
The DataGramsocket class DataGramsocket class creates a self-address socket to communicate with the server side in the client, and sends and accepts the 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.javaimport 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 caled. The // converness 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 an inetaddress Object. // That Object Contains the ip address of the host and is // buy by datagrampacket. inetaddress = inetaddress.getbyname (Host); // CRE ate 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); // Send 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 storet. System.out.println (new string (dgp.getdata ()));} catch (ooexception e) {system.out.println (E.TOString ());} finally {if (s! = null) s.close ();}}} DGSCLIENT starts with a DataGramsocket object that creates a binding or a client (client) port, then load the belt There is a reference to the InetAddress subclass of text information, and the server host IP address is referenced. Next, DGSClient creates a DataGrampacket object, which adds a reference to the buffer with text information, reference to the inetaddress sub-object, And the service port number 10000, the self-adding data package of DataGrampacket is sent to the server program through method SENT (), so a new DataGrampacket object containing a service program response is created. Receive () get the response from the self-adder data package, then The getData () method of the data package is returned to 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.javaimport java.io *; import java.net *; class DGSServer {public static void main (String [] args) throws IOException {System.out.println ( "Server starting... ../n "); // Create a datagram socket bound to port 10000. Datagram // packets sent from client 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-adder socket of a binding port 1000, then create a byte array Accommoding self-addressing information, and creates a self-address package, the next step, DGSServer enters an infinite loop to receive the self-addressing packet, display the content and return to the client, and the self-adding socket 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-Distance and MulticastSocket classes The example shows the server program thread to send a single message (through the flow sleeve text or self-address socket) to the unique client program, this behavior is called single point transfer (Unicasting) ), Most of the cases are not 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 about 100 billion bytes of data to customers. Diffuse program, use single point transfer, then each client must copy a data, if you have 10,000 clients on the Internet, you need to send 10000G data over the Internet, which is inevitably Network blocking, reducing the transmission speed of the network. 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 parameters) to receive self-address packs, ports 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.javaimport 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 used . 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 Da TAGRAM PACKET. S.RECEIVE (DGP); // Create A Second Byte Array With A Length That Matches // THE Length2 = 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 Used.) 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.javaimport java.io *; import java.net *; class MCServer {public static void main (String [] args) throws IOException {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