«Back to Home

Core Java

Topics

DatagramSocket And DatagramPacket Classes In Java

DatagramSocket And DatagramPacket Classes
 
The DatagramSocket class and DatagramPacket class are used for the connection-less socket programming in Java.
 
DatagramSocket class

The DatagramSocket class shows a connection-less socket to send and receive the datagram packets.
 
A datagram is mainly an information but there is no guarantee of its content and arrival or an arrival time.
 
Constructors of DatagramSocket class

DatagramSocket() throws SocketException

This constructor creates a datagram socket and binds it with the available port number on the localhost machine.
 
DatagramSocket(int port) throws SocketException

This constructor creates a datagram socket and binds it with the given port number.
 
DatagramSocket(int port, InetAddress address) throws SocketException

This constructor creates a datagram socket, binds it with the particular port number and the host address.
 
DatagramPacket class

The DatagramPacket is a message, which can be sent or received. If we send the multiple packets, it may arrive in any order. In addition, the packet delivery is not guaranteed.
 
Constructors of DatagramPacket class

DatagramPacket(byte[] barr, int length)

This constructor creates a datagram packet and it is used to receive the packets.
 
DatagramPacket(byte[] barr, int length, InetAddress address, int port)

This constructor creates a datagram packet and it is used to send the packets.
 
Let’s see an example, given below to send DatagramPacket through DatagramSocket.
 
Code
  1. import java.net.*;  
  2. public class DataSenderExample {  
  3.     public static void main(String[] args) throws Exception {  
  4.         DatagramSocket ds = new DatagramSocket();  
  5.         String st = " Welcome To My World ";  
  6.         InetAddress ip = InetAddress.getByName("127.0.0.1");  
  7.         DatagramPacket dp = new DatagramPacket(st.getBytes(), st.length(), ip, 1000);  
  8.         ds.send(dp);  
  9.         ds.close();  
  10.     }  
  11. }  
13

Let’s see an example, given below to receive DatagramPacket through DatagramSocket.
 
Code
  1. import java.net.*;  
  2. public class DataReceiverExample {  
  3.     public static void main(String[] args) throws Exception {  
  4.         DatagramSocket ds = new DatagramSocket(1000);  
  5.         byte[] b = new byte[1024];  
  6.         DatagramPacket dp = new DatagramPacket(b, 1024);  
  7.         ds.receive(dp);  
  8.         String st = new String(dp.getData(), 0, dp.getLength());  
  9.         System.out.println(st);  
  10.         ds.close();  
  11.     }  
  12. }  
14

Summary

Thus, we learnt that Java DatagramSocket class and DatagramPacket class are used for the connection-less socket programming and also learnt how we can use it in Java.