Switch to Java socket programming (below)

Source: Internet
Author: User
Custom socket)

Because it takes a certain amount of time to use each connection of the stream socket, to reduce this overhead, the Network API provides the second socket: Self-addressing socket (datemedisocket ), self-addressing uses 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 multiple IP address information packets can be sent through the self-addressing socket, the self-addressing information is included in the self-addressing package, and the self-addressing package is included in the IP package, which limits the addressing information length to 60000 bytes. Figure 2 shows the self-addressing information of the Self-addressing Package located in the IP package.

Unlike TCP, UDP provides another method to ensure that the information package does not reach the destination ,, UDP will not request the sender to resend the self-addressing packet because UDP contains error detection information in each self-addressing packet, after each self-addressing packet arrives at the destination, UDP only performs a simple error check. If the check fails, UDP will discard the self-addressing packet and will not request the replacement from the sender, this is similar to sending a mail through the Post Office. The sender does not need to establish a connection with the recipient before sending the mail, nor can it ensure that the mail can arrive at the recipient.

The work of the Self-addressing socket includes the following three classes: datagrampacket, datagramsocket, and multicastsocket. The initrampacket object depicts the address information of the Self-addressing package. initramsocket indicates the self-addressing socket of the customer program and the service program, and multicastsocket depicts the self-addressing socket capable of multi-point transfer, these three classes are located in the java.net package.

  Datagrampacket class

Before using a self-addressing package, you must first familiarize yourself with the datagrampacket class. Address information and the Self-addressing package are compressed into the objects created by this class in byte arrays at the same time.

Datagrampacket has several constructors. Even though these constructors have different forms, they usually have two common parameters: byte [] buffer and INT length, the buffer parameter contains a reference to the byte array that stores the information of the Self-addressing data packet. Length indicates the length of the byte array.

The simplest constructor is mongorampacket (byte [] buffer, int length). This constructor determines the length of the Self-addressing data packet array and array, however, there is no address or port information for the Self-addressing data packet. You can call the setaddress (inetaddress ADDR) and setport (INT port) Methods to add the information, the following code demonstrates these functions and methods.

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 datemedipacket to Port 6000.

If you prefer to include both the address and port number when calling the constructor, you can use the mongorampacket (byte [] buffer, int length, inetaddress ADDR, int port) 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 );

You can call the setdata (byte [] buffer) and setlength (INT length) Methods to change the byte array and its length after creating the initrampacket object. You can call getdata () to obtain the byte array reference at any time, and call getlength () to obtain the length of the byte array. The following code demonstrates these methods:

Byte [] buffer2 = new byte [1, 256];
DGP. setdata (buffer2 );
DGP. setlength (buffer2.length );

For more information about datagrampacket, see the SDK documentation.

Datagramsocket class

The initramsocket class creates a self-addressing socket on the client to communicate with the server, and sends and accepts the self-addressing socket. Although there are multiple constructors to choose from, I found that the most convenient choice for creating a client self-addressing socket is the mongoramsocket () function, while the server side is the mongoramsocket (INT port) function, if you fail to create a self-addressing socket or bind the self-addressing socket to the local port, both functions will throw a socketexception object. Once the program creates a semi-ramsocket object, then the program calls send (mongorampacket DGP) and receive (mongorampacket DGP) respectively to send and receive self-addressing data packets,

The dgsclient source code displayed in list4 demonstrates how to create a self-addressing socket and how to process sending and receiving 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 datatesocket bound to an arbitrary port.

S = new datagramsocket ();

// Create a byte array that will hold the data portion of
// Datemedipacket's message. That message originates as
// String object, which gets converted to a sequence
// Bytes when string's getbytes () method is called.
// Conversion uses the platform's default character set.

Byte [] buffer;
Buffer = new string ("Send me a datax"). 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 IA = inetaddress. getbyname (host );

// Create a datagrampacket object that encapsulates
// Reference to the byte array and Destination Address
// Information. The destination address consists of
// 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 datax packet over the socket.

S. Send (DGP );

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

Byte [] buffer2 = new byte [1, 100];

// Create a random rampacket object that specifies a buffer
// To hold the server program's response, the IP address
// The server program's computer, and port number 10000.

DGP = new datagrampacket (buffer2,
Buffer. length,
IA,
10000 );

// Receive a datatipacket over the socket.

S. Receive (DGP );

// Print the data returned from the server program and stored
// In the datemedipacket.

System. Out. println (new string (DGP. getdata ()));

}
Catch (ioexception E)
{
System. Out. println (E. tostring ());
}
Finally
{
If (s! = NULL)
S. Close ();
}
}
}

Dgsclient starts by creating an initramsocket object bound to any local (client) port, then loading the Array Buffer with text information and referencing the inetaddress subclass object that describes the Server Host IP address. Next, dgsclient creates an initrampacket object, which is added to the reference of the buffer with text information, the reference of the inetaddress subclass object, and the self-addressing data packet passing method sent () of the Service port number 10000 and datagrampacket () then, a new initrampacket object containing the response of the service program is created. Receive () obtains the response self-addressing data packet, and then getdata () of the Self-addressing data packet () method to return a reference of the Self-addressing data packet, and disable the datagramsocket.

The dgsserver service program supplements the dgsclient deficiency. 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 ioexception
{
System. Out. println ("server starting.../N ");

// Create a datax socket bound to port 10000. datax
// Packets sent from client programs arrive at this port.

Datagramsocket S = new datagramsocket (10000 );

// Create a byte array to hold data contents of dataphin
// Packet.

Byte [] DATA = new byte [100];

// Create a datagrampacket object that encapsulates a reference
// To the byte array and destination address information.
// 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 datatipacket from the client program.

S. Receive (DGP );

// Display contents of datemedipacket.

System. Out. println (new string (data ));

// Echo datemedipacket back to client program.

S. Send (DGP );
}
}
}

Dgsserver creates a self-addressing socket bound to port 10000, creates a byte array to accommodate self-addressing information, and creates a self-addressing package. Next, the dgsserver enters an infinite loop To receive the self-addressing packet, display the content, and return the response to the client. The self-addressing package is not closed because the loop is infinite.

After compiling the source code of dgsserver and dgsclient, enter Java dgsserver to start running dgsserver, and enter Java dgsclient on the same host to run dgsclient. If dgsserver and dgsclient run on different hosts, add the host name or IP address of the service program to the command line, for example, Java dgsclient www.yesky.com.

Multi-Point transmission and multicastsocket

The preceding example shows that the server program thread sends a single message (through a stream socket or a self-addressing socket) to a unique client program. This behavior is called unicasting ), in most cases, it is not suitable for single-point transmission. For example, a rock artist plays a concert over the Internet. The quality of pictures and sounds depends on the transmission speed, the server program needs to transmit about 1 billion bytes of data to the client program. With Single-point transmission, each client program needs to copy one copy of data. If, if 10000 clients on the internet want to watch the concert, then the server program needs to transmit the listen G data over the Internet, which will inevitably lead to network congestion and reduce the network transmission speed.

If the server program sends the same information to multiple clients, the server program and client program can use multi-point transmission (multicasting) for communication. Multi-Point transfer means that the service program sends a series of self-addressing data packets to the IP address and port of the dedicated multi-point Transfer Group. It is registered by the multi-point transfer socket by adding the operation IP address, at this point, the customer program can receive the Self-addressing package sent to the group (the customer program can also send the self-addressing package to the group ), once the customer program completes all the self-addressing data 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 (included) are reserved Multicast Group addresses.

Network APIs use the multicastsocket class, multicastsocket class, and some auxiliary classes (such as networkinterface) to support multi-point transfer. When a customer program is added to a multi-point Transfer Group, a multicastsocket object is created. The multicastsocket (INT port) constructor allows an application to specify a port (through the port parameter) to receive a self-addressing packet. The port must match the port number of the service program and be added to the multi-point transfer group, the customer program calls one of the two joingroup () methods and also calls one of the two leavegroup () Methods to exit the transfer group.

Because multicastsocket extends the initramsocket class, a multicastsocket object has the right to access the initramsocket method.

List6 is the source code of mcclient. This Code demonstrates an example of adding a client to a multicast 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 the 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
// Datagrampacket.

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

// Join the multicast group so that datatipackets can be
// Received.

S. joingroup (group );

// Read several datatepackets from the server program.

For (INT I = 0; I <10; I ++)
{
// No line will exceed 256 bytes.

Byte [] buffer = new byte [256];

// The specified rampacket object needs no addressing
// Information because the socket contains the address.

Datagrampacket DGP = new datagrampacket (buffer,
Buffer. Length );

// Receive a datatipacket.

S. Receive (DGP );

// Create a second byte array with a length that matches
// The length of the sent data.

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 used .)

System. Out. println (new string (buffer2 ));
}

// Leave the multicast group.

S. leavegroup (group );

// Close the socket.

S. Close ();
}
}

Mcclient creates a multicastsocket object bound to port 10000, and then obtains an inetaddress subclass object that contains the IP address 231.0.0.0 of the multicast group, and then uses joingroup (inetaddress ADDR) the method is added to the multi-point transfer group. Next, mcclient receives 10 self-addressing packages and outputs their content. Then, it uses the leavegroup (inetaddress ADDR) method to exit the transfer group and closes the socket.

Maybe you are surprised to use two byte arrays buffer and buffer2. When a self-addressing package is received, the getdata () method returns a reference. The length of the Self-addressing package is 256 bytes, if you want to output all the data, there will be many spaces after the actual data is output, which is obviously unreasonable, so we must remove these spaces, so we create a small byte array buffer2, the actual length of buffer2 is the actual length of the data. You can obtain this length by calling the datagrampacket's getlength () method. To quickly copy the length of getlength () from buffer to buffer2, call 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 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.

  
// Datagramsocket S = new datagramsocket ();

// Obtain an inetaddress object that contains the Multicast
// Group address 231.0.0.1. The inetaddress object is used
// 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
// Multicast group address (as stored in the inetaddress object)
// And port number 10000 -- the port to which multicast datasync
// Packets are sent. (Note: The dummy array is used to prevent
// Nullpointerexception object being thrown from
// 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 character set is used to convert from Unicode
// Characters to bytes.

Byte [] buffer = ("video line" + I). getbytes ();

// Establish the byte array as the datatepacket's
// Buffer.

DGP. setdata (buffer );

// Establish the byte array's length as the length of
// Datatepacket's buffer.

DGP. setlength (buffer. Length );

// Send the datax to all members of the multicast group
// That listen on port 10000.

S. Send (DGP );
}

// Close the socket.

S. Close ();
}
}

Mcserver creates a multicastsocket object. Because it is part of the initrampacket object, it does not bind a port number. initrampacket has a multicast group IP address (231.0.0.0). Once the initrampacket object is created, the mcserver enters a cycle of sending 30000 lines of text. A byte array is created for each line of text, and their references are stored in the initrampacket object created earlier, the send () method is used to send a self-addressing package to all group members.

After mcserver and mcclient are compiled, input Java mcserver to start running mcserver, and then run one or more mcclients.

  Conclusion

This article reveals the Java Network API application method by studying sockets. We introduce the composition of the nested inetaddress and socket, the stream socket and the Self-addressing socket, and how to use inetaddress, socket, serversocket, datagrampacket, datagramsocket, and multicastsocket. After completing this article, you can write basic underlying communication programs.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.