JDK (Java Development Kit) Tutorials
Dr. Herong Yang, Version 5.00

Establishing a Datagram Communication Link

This section describes how to establish a datagram communication link. A server application runs a datagram socket in listen mode and a client application connects a client socket to the server socket.

To establish a datagram communication link, one application program must act as a receiver, create a datagram socket with a given local port number, and set the datagram socket in the receiving mode waiting for a datagram to arrive.

With receiver program running and waiting for a datagram to arrive, the other program can now act as a sender, create a datagram socket with a given local port number, prepare a datagram with the remote address and port number in in, and send it over.

J2SDK offers two main classes to support datagram communication:

1. java.net.DatagramSocket with methods:

  • DatagramSocket(): constructing a datagram socket with a given local address, and a given local port number.
  • receive(): waiting for a datagram to arrive, and returning the datagram to the caller.
  • send(): sending a datagram through the datagram socket.

2. java.net.DatagramPacket representing the datagram with methods:

  • getAddress(): getting the remote address from the datagram.
  • getPort(): getting the remote port number from the datagram.
  • getData(): getting the data from the datagram.
  • setAddress(): setting the remote address to the datagram.
  • setPort(): setting the remote port to the datagram.
  • setData(): setting the data to the datagram.

The following diagram shows steps involved in sending a datagram from one program to another program using the methods provided by DatagramSocket and DatagramPacket classes:

       Sender Program              Receiver Program
       Internet Address #a         Internet Address #b
Step   Available Port #p           Available Port #q

1                                  ds = new DatagramSocket(#b+#q)
2                                  dp = new DatagramPacket()
3                                  ds.receive(dp)
4      ds = new DatagramSocket()   (waiting)
5      dp = new DataPacket()       (waiting)
6      dp.setAddress()             (waiting)
7      dp.setPort()                (waiting)
8      dp.setData()                (waiting)
9      ds.send(dp)                 (receiving datagram)
10                                 (dp is ready)

Last update: 2006.

Sections in This Chapter

What Is a Datagram?

Establishing a Datagram Communication Link

DatagramServer.java - A Datagram Server Application

DatagraClient.java - A Datagram Client Application

Dr. Herong Yang, updated in 2008
Establishing a Datagram Communication Link