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
DatagramSocket()
throwsSocketException
;-
It creates a datagram socket and binds it with the available Port number on Local Machine.
-
DatagramSocket(int port)
throwsSocketException
; -
It creates a datagram socket and binds it with the given port number.
-
Datagram(int port, InetAddress address)
throwsSocketException
; - 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
DatagramPacket(byte[] byteArray, int length)
- It creates a datagram packet to recieve the packets.
DatagramPacket(byte[] byteArray, InetAddress address int length)
- 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();
}
}