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.

Constructor

  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.

Constructor

  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

import java.io.*;
import java.net.*;

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

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

        ds.send(dp);
        ds.close();
    }
}

Receiver Implementation

import java.io.IOException;
import java.net.*;

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);
        ds.receive(dp);

        String str = new String(dp.getData(), 0, dp.getLength());
        System.out.println(str);
        ds.close();
    }
}