Home > Articles > Programming > Java

Like this article? We recommend

Like this article? We recommend

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".

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020