Skip to content

Connection Less

    1. Datagram Socket Class
    2. Datagram Packet Class

DatagramSocket Class

  • This class represents a connection-less socket for sending and receiving datagram packets.
  • A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.


  1. DatagramSocket() throws SocketException;
  2. It creates a datagram socket and binds it with the available Port number on Local Machine.

  3. DatagramSocket(int port) throws SocketException;

  4. It creates a datagram socket and binds it with the given port number.

  5. Datagram(int port, InetAddress address) throws SocketException;

  6. It binds with the specified port and host address.

DatagramPacket Class

  • DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.


  1. DatagramPacket(byte[] byteArray, int length)
  2. It creates a datagram packet to recieve the packets.
  3. DatagramPacket(byte[] byteArray, InetAddress address int length)
  4. It is used to send the packets.

Sender Implementation


public class Sender {
    public static void main(String[] args) throws Exception{
        DatagramSocket ds = new DatagramSocket(6666);
        String str = "Welcome Java";
        InetAddress ip = InetAddress.getByName("");

        DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(),ip, 3000);


Receiver Implementation


public class Receiver {
    public static void main(String[] args) throws IOException{

        DatagramSocket ds = new DatagramSocket(6666);

        byte[] buf = new byte[1024];

        DatagramPacket dp = new DatagramPacket(buf, 1024);

        String str = new String(dp.getData(), 0, dp.getLength());