A datagram socket is used to send and receive datagram packets. A DatagramSocket object is a local connection to a port that does the sending and receiving. There is no distinction between a UDP socket and a UDP server socket. Also unlike TCP sockets, a DatagramSocket can send to multiple, different addresses. The address to which data goes is stored in the packet, not in the socket. Some applications that you write to communicate over the network will not require the reliable, point-to-point channel provided by TCP. Rather, your applications might benefit from a mode of communication that delivers independent packages of information. The DatagramPacket and DatagramSocket classes in the java.net package implement system-independent datagram communication using UDP. A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.

Java’s support for UDP is contained in two classes:


It is used for receiving data packets. Following are the constructors of this class.

  • public DatagramSocket() throws SocketException
  • public DatagramSocket(int port) throws SocketException
  • public DatagramSocket(int port, InetAddress laddr) throws SocketException


It is used for creating and sending data packets.

  • public DatagramPacket(byte[] data, int length)
  • public DatagramPacket(byte[] data, int length, InetAddress iaddr, int iport)


In this example, wrapper for an array of bytes from which data will be sent or into which data will be received also contains the address and port to which the packet will be sent.

String s = "My first UDP Packet"
byte[] b = s.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length);

Example -2

try {
	 InetAddress uni = new InetAddess("sourcecodemania.com");
 	int num = 4321;
 	String s = "My second UDP Packet"
	 byte[] b = s.getBytes();
 DatagramPacket dp = new DatagramPacket(b, b.length, uni, num);
catch (UnknownHostException e) {

Sending a Datagram Packet

To send data to a particular server:

  1. Convert the data into byte array
  2. Pass this byte array, the length of the data in the array (most of the time this will be the length of the array) and the InetAddress and port to which you wish to send it into the DatagramPacket() constructor.
  3. Next create a DatagramSocket and pass the packet to its send() method

Example: Sending a packet

InetAddress uni= new InetAddess("sourcecodemania.com");
int num = 4321;
String s = "My second UDP Packet";
byte[] b = s.getBytes();
DatagramPacket  dp = new DatagramPacket(b, b.length, uni, num);
DatagramSocket  sender = new DatagramSocket();

Receiving UDP Datagrams

To receive UDP datagram packet:

  1. Construct a DatagramSocket object on the port on which you want to listen.
  2. Pass an empty DatagramPacket object to the DatagramSocket’s receive() method.
    • public synchronized void receive(DatagramPacket dp) throws IOException
  3. The calling thread blocks until a datagram is received.
  4. dp is filled with the data from that datagram.
  5. Use getPort() and getAddress() to tell where the packet came from,
  6. getData() to retrieve the data, and getLength() to see how many bytes were in the data.
  7. If the received packet was too long for the buffer, it’s truncated to the length of the buffer.
  8. Length is reset when packet is received

Example: Receiving UDP Datagrams

try {
 byte buffer = new byte[65536];
 DatagramPacket  incoming = new DatagramPacket(buffer, buffer.length);
 DatagramSocket  ds = new DatagramSocket(4321);
byte[] data = incoming.getData();
 String s = new String(data, 0, data.getLength());
System.out.println("Port" + incoming.getPort() + " on " + incoming.getAddress() + " sent this message:");
 catch (IOException e) {
	System.err.println(e); }
class netFunctions {
  public static void main (String args[]) {
    try {
     InetAddress address = InetAddress.getByName("sourcecodemania.com");
     InetAddress addlocal= InetAddress.getLocalHost();
     InetAddress localname = InetAddress.getLocalHost();
          System.out.println("Hello. My name is " +  localname.getHostName());
    catch (UnknownHostException e) {
   	   System.out.println("Could not find site");


       Hello. My name is sourcecodemania-dcefc1406

Stream Socket vs. Datagram Socket

Stream Socket:

  • A dedicated point-to-point channel between a client and server.
  • Use TCP (Transmission Control Protocol) for data transmission.
  • Lossless and reliable.
  • Sent and received in the same order.

Datagram Socket:

  • No dedicated point-to-point channel between a client and server.
  • Use UDP (User Datagram Protocol) for data transmission.
  • May lose data and not 100% reliable.
  • Data may not received in the same order as sent.

Client Server Example

We will write a program that collects student information from a client and send them to a server. We will passing students information in an object.

Student Class

public class Student implements java.io.Serializable
 { private String name;
private String street;
private String city;
private String state;
private String zip;
public Student(String name, String street, String city, String state, String zip)
 this.name = name; 	this.street = street;
this.city = city; 		this.state = state; 		this.zip = zip; }
public String getName() { return name; }
public String getStreet() { return street; }
public String getCity() { return city; }
public String getState() { return state; }
public String getZip() { return zip; }


public class StudentServer {
private ObjectOutputStream outputToFile;
private ObjectInputStream inputFromClient;
public static void main(String[] args) {
 new StudentServer(); }
public StudentServer() {
try { // Create a server socket
ServerSocket serverSocket = new ServerSocket(8000); System.out.println("Server started ");
// Create an object ouput stream
outputToFile = new ObjectOutputStream( new FileOutputStream("student.dat", true));
while (true) {
// Listen for a new connection request
Socket socket = serverSocket.accept();
inputFromClient = new ObjectInputStream(socket.getInputStream());
object = inputFromClient.readObject();
// Write to the file
System.out.println("A new student object is stored"); }
catch(ClassNotFoundException ex) {
ex.printStackTrace(); }
catch(IOException ex) {
ex.printStackTrace(); }
finally {
try { inputFromClient.close();
outputToFile.close(); }
catch (Exception ex) {
ex.printStackTrace(); }
} } }


public class StudentClient extends JApplet {
private JTextField jtfName = new JTextField(32);
private JTextField jtfStreet = new JTextField(32);
private JTextField jtfCity = new JTextField(20);
private JTextField jtfState = new JTextField(2);
private JTextField jtfZip = new JTextField(5);
// Button for sending a student to the server
private JButton jbtRegister = new JButton("Register to the Server");
String host = "localhost";
public void init() {
// Panel p1 for holding labels Name, Street, and City
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3, 1));
p1.add(new JLabel("Name"));
p1.add(new JLabel("Street"));
p1.add(new JLabel("City"));
// Panel jpState for holding state
JPanel jpState = new JPanel();
jpState.setLayout(new BorderLayout());
jpState.add(new JLabel("State"), BorderLayout.WEST);
jpState.add(jtfState, BorderLayout.CENTER);
// Panel jpZip for holding zip
 JPanel jpZip = new JPanel();
jpZip.setLayout(new BorderLayout());
jpZip.add(new JLabel("Zip"), BorderLayout.WEST);
jpZip.add(jtfZip, BorderLayout.CENTER);
// Panel p2 for holding jpState and jpZip
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.add(jpState, BorderLayout.WEST);
p2.add(jpZip, BorderLayout.CENTER);
//….. Same  for other widgets
// Place p1 and p4 into StudentPanel
JPanel studentPanel = new JPanel(new BorderLayout());
studentPanel.setBorder(new BevelBorder(BevelBorder.RAISED));
studentPanel.add(p1, BorderLayout.WEST);
studentPanel.add(p4, BorderLayout.CENTER);
// Add the student panel and button to the applet
add(studentPanel, BorderLayout.CENTER);
add(jbtRegister, BorderLayout.SOUTH);
jbtRegister.addActionListener(new ButtonListener());
private class ButtonListener implements ActionListener {
 public void actionPerformed(ActionEvent e) {
try {
// Establish connection with the server
Socket socket = new Socket(host, 8000);
ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream());
// Get text field
String name = jtfName.getText().trim();
String street = jtfStreet.getText().trim();
String city = jtfCity.getText().trim();
String state = jtfState.getText().trim();
String zip = jtfZip.getText().trim();
// Create a Student object and send to the server
Student s = new Student (name, street, city, state, zip);
catch (IOException ex) { System.err.println(ex); } } }
public static void main(String[] args) {
 // Create a frame
 JFrame frame = new JFrame("Register Student Client");
// Create an instance of the applet
StudentClient applet = new StudentClient();
// Add the applet instance to the frame
frame.add(applet, BorderLayout.CENTER);
// Display the frame
frame.setVisible(true); } }

Related Posts

Tagged with: ClassesJAVAObject OrientedProgrammingSource Code

4 Responses to UDP Datagram Sockets in Java

  1. Sameer Jain says:

    how to use Japplet in this particular example

  2. Martin Meys says:

    Thanks for this great article, it helps me a lot!

    However, I noticed a little mistake : in the example “Receiving UDP Datagrams”, at line 7, it is “incoming.getLength()” and not “data.getLength()”

  3. Anonymous says:

    Thank you for the help.Now I understood how UDP works

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds