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
- import java.net.*;
- public class DataSenderExample {
- public static void main(String[] args) throws Exception {
- DatagramSocket ds = new DatagramSocket();
- String st = " Welcome To My World ";
- InetAddress ip = InetAddress.getByName("127.0.0.1");
- DatagramPacket dp = new DatagramPacket(st.getBytes(), st.length(), ip, 1000);
- ds.send(dp);
- ds.close();
- }
- }
Let’s see an example, given below to receive DatagramPacket through DatagramSocket.
Code
- import java.net.*;
- public class DataReceiverExample {
- public static void main(String[] args) throws Exception {
- DatagramSocket ds = new DatagramSocket(1000);
- byte[] b = new byte[1024];
- DatagramPacket dp = new DatagramPacket(b, 1024);
- ds.receive(dp);
- String st = new String(dp.getData(), 0, dp.getLength());
- System.out.println(st);
- ds.close();
- }
- }
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.