Home > Articles

  • Print
  • + Share This
  • 💬 Discuss

Working with Datagram Sockets

For some programs (such as a program that needs current date/time information or a network-based game that notifies all players when someone joins the game or leaves the game), the overhead incurred by using stream sockets is unacceptable. After all, it takes a certain amount of time for a client program to establish a connection with a server program. To reduce the overhead, the Network API supplies a second kind of socket: the datagram socket. A datagram socket uses UDP to send a datagram (a short message) from a client program to a server program, or from a server program to a client program. Unlike multi-IP packet messages that can be sent via stream sockets, a datagram must fit inside a single datagram packet. Furthermore, the datagram packet must fit inside a single IP packet. That limits the maximum length of a datagram to around 60,000 bytes. Figure 2 illustrates a datagram within a datagram packet, which is itself within an IP packet.

Figure 2 An IP packet encapsulates a datagram package, which encapsulates a datagram.

Unlike TCP, which guarantees that a message arrives at the message's destination (regardless of whether IP packets get lost or contain errors), UDP offers no such guarantee. If a datagram packet does not arrive at its destination, UDP does not request that a sender resend the datagram packet. Because UDP maintains some error-checking information in each datagram packet, UDP performs simple error checking on each datagram packet that arrives at the destination. If the datagram packet fails the error check, UDP discards that datagram packet; UDP does not request a replacement datagram packet from the sender. This scenario is analogous to mailing a letter. The sender does not need to establish a connection with the letter's recipient before mailing the letter. Also, there is no guarantee that the letter will arrive.

This section works with datagram sockets in the context of three classes: DatagramPacket, DatagramSocket, and MulticastSocket. DatagramPacket objects represent individually addressable datagram packets, DatagramSocket objects represent client program and server program datagram sockets, and MulticastSocket objects represent datagram sockets that make it possible for client programs to participate in multicasting. (You will learn about multicasting later in this article.) All three classes belong to the java.net package.

The DatagramPacket Class

Before you can send datagram packets, you need to become familiar with the DatagramPacket class. Objects created from that class encapsulate datagram packets as byte arrays along with addressing information.

A close look at DatagramPacket reveals several constructors. Even though the constructors differ in some way from each other, all of them share two parameters in common—byte [] buffer and int length. The buffer parameter contains a reference to an array of bytes that holds the datagram, and length determines the actual number of bytes (starting at array index 0) that constitutes the datagram.

The simplest constructor is DatagramPacket(byte [] buffer, int length). That constructor identifies the datagram's byte array and length, but it says nothing about the datagram packet's address and port. That information can later be added by calling methods setAddress(InetAddress addr) and setPort(int port). The following code fragment demonstrates the constructor 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 datagram packet to port 6000.

If you prefer to include a datagram packet's address and port number when calling a constructor, you can take advantage of DatagramPacket(byte [] buffer, int length, InetAddress addr, int port). The following code fragment demonstrates an alternative to the previous code fragment:

byte [] buffer = new byte [100];
InetAddress ia = InetAddress.getByName ("www.disney.com");
DatagramPacket dgp = new DatagramPacket (buffer, buffer.length, ia, 
                                         6000);

Occasionally, you might find yourself wanting to change the byte array reference and length after creating a DatagramPacket object. That can be accomplished by calling the setData(byte [] buffer) and setLength(int length) methods, respectively. At any time, you can obtain a reference to the current byte array by calling getData() and the current length by calling getLength(). Those methods are demonstrated in the following code fragment, which builds upon the previous code fragment:

byte [] buffer2 = new byte [256];
dgp.setData (buffer2);
dgp.setLength (buffer2.length);

Consult the SDK documentation to learn more about DatagramPacket.

The DatagramSocket Class

The DatagramSocket class creates datagram sockets on the client program and server program sides of a communication link, and sends and receives datagram packets. Although there are several constructors from which to choose, I find it convenient to choose the DatagramSocket() constructor for creating a datagram socket on the client program side and the DatagramSocket(int port) constructor for creating a datagram socket on the server program side. Either constructor throws a SocketException object if it cannot create the datagram socket or bind the datagram socket to a local port. Once a program creates a DatagramSocket object, the program calls send(DatagramPacket dgp) and receive(DatagramPacket dgp) to send and receive datagram packet, respectively.

Listing 4's DGSClient source code demonstrates the creation of a datagram socket and the process of sending and receiving messages over that 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 ia = 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);

          // 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 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 begins by creating a DatagramSocket object that binds to an arbitrary local (client) port number. It then populates a buffer with a text message and obtains a reference to an InetAddress subclass object that represents the IP address of the server host. Continuing, DGSClient creates a DatagramPacket object that encapsulates the text message buffer's reference, the InetAddress subclass object reference, and server port number 10,000. The DatagramPacket's datagram is sent to the server program via send(). A new DatagramPacket object is created, along with a byte array that holds the server program's response. The receive() method obtains the response datagram packet, and the datagram packet's getData() method returns a reference to the datagram (which prints). Finally, the DatagramSocket closes.

The DGSServer server program that complements DGSClient is pretty simple. Listing 5 presents DGSServer's source code.

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 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 datagram socket that binds to port 10,000. It then creates a byte array for holding a datagram and creates a datagram packet. DGSServer next enters an infinite loop to receive datagram packets, display their datagrams, and echo the datagram packets back to the client program. The datagram socket is not closed because the loop is infinite.

After compiling the source code to DGSServer and DGSClient, start DGSServer by typing java DGSServer. Then run DGSClient on the same host by typing java DGSClient. If DGSServer is running on a different host than DGSClient, specify the server program's hostname or IP address as a command-line argument to java DGSClient. For example, if www.cnn.com is the server program's hostname, type java DGSClient www.cnn.com.

TIP

For another example of datagram packets and datagram sockets, read the JavaWorld article "Java Tip 40: Object Transport via Datagram Packets".

Multicasting and the MulticastSocket Class

Previous examples showed a server program thread sending a single message (via stream or datagram sockets) to one and only one client program. That activity is known as unicasting. Some situations are not appropriate to unicasting. For example, imagine that a rock musician holds a benefit concert that will be transmitted over the World Wide Web. Depending on the quality of the video and audio feed (and its length), a server program might need to transmit around a gigabyte (a billion bytes) to a client program. Using unicasting, each client program requires its own copy of the data. For example, if 10,000 individuals want to view the concert over the World Wide Web, the server program must transmit approximately 10,000GB of data across the Internet. That excess network traffic has the potential to slow down much Internet traffic.

For situations in which the same message needs to be transmitted to many client programs, server and client programs can take advantage of multicasting (the capability of a server program to send one copy of a message to multiple client programs). To multicast, a server program sends a sequence of datagram packets to a special IP address—a multicast group address—and a specific port (as indicated by a port number). Client programs that want to receive those datagram packets create a multicast socket using that port number. The IP address is registered with the multicast socket via a join group operation. At that point, the client program can receive datagram packets that are sent to the group. (The client program can also send datagram packets to the group.) Once the client program has read all the datagram packets that it needs to read, it removes itself from the group by applying a leave group operation against the multicast socket.

NOTE

IP addresses 224.0.0.1 to 239.255.255.255 (inclusive) are reserved for use as multicast group addresses.

The Network API supports multicasting via class MulticastSocket, along with InetAddress and some minor classes (such as NetworkInterface). When a client program needs to join a multicast group, it creates an object from MulticastSocket. The MulticastSocket(int port) constructor allows the client program to specify the number of the port (via the port argument) over which it will receive datagram packets. That port number must match the server program's port number. To join a group, the client program calls one of two joinGroup() methods. To leave the group, the client program calls one of two leaveGroup() methods.

Because MulticastSocket extends DatagramSocket, a MulticastSocket object has access to DatagramSocket methods. The only new methods that you will probably need to work with are the previously mentioned joinGroup() and leaveGroup() methods.

Listing 6's MCClient source code presents an example of a client program joining 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 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 datagram packet.

           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 that's bound to port 10,000. It next obtains an InetAddress subclass object containing multicast group IP address 231.0.0.1. That object is used to join the group via joinGroup(InetAddress addr). MCClient next receives 10 datagram packets, prints their contents, and leaves the group via leaveGroup(InetAddress addr). Finally, the socket is closed.

You might be curious about the need for two byte arrays, buffer and buffer2. When a datagram packet is received, the getData() method returns a reference to its datagram. The length of that datagram is exactly 256 bytes, as specified by the server program (which you will shortly investigate). If you try to print all those bytes, you will see a lot of empty spaces after the actual data. You can eliminate those spaces by creating a smaller byte array—buffer2—that has the exact length of the actual data. To get that length, call DatagramPacket's getLength() method. For a fast way to copy the first getLength() bytes from buffer to buffer2, call System.arraycopy().

It's time to investigate the server program. Listing 7's MCServer source code shows how that server 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 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 character set is used to convert from Unicode
           // 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 creates a MulticastSocket object. No port number needs to bind to the multicast socket because it is specified as part of a DatagramPacket object, along with the multicast group's IP address (231.0.0.1). Once the DatagramPacket object has been created, MCServer enters a loop that sends 30,000 lines of text. For each line of text, a byte array is created, and its reference is stored inside the previously created DatagramPacket object. The datagram packet is sent to all group members via send().

After compiling the MCServer and MCClient source code, log onto the Internet. Start MCServer by typing java MCServer. Finally, run one or more copies of MCClient by typing java MCClient.

TIP

For another multicasting example, read the JavaWorld article "Multicast the Chatwaves".

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus