java tutorial - DatagramSocket | java DatagramSocket | DatagramPacket - java programming - learn java - java basics - java for beginners



  • Java DatagramSocket and DatagramPacket is a connection-less socket programming model.

Java DatagramSocket

  • DatagramSocket is used to send and receive datagram packets.
  • It creates a datagram socket and binds up with the existing Port Number on the localhost machine.
 Java DatagramSocket

Learn Java - Java tutorial - Java DatagramSocket - Java examples - Java programs

Constructors of DatagramSocket class

  • DatagramSocket() throws SocketEeption: it creates a datagram socket and binds up the given Port Number.
  • DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds up with the specified port number and host address.
  • DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it with the specified port number and host address.

Java DatagramPacket

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

Learn Java - Java tutorial - Java DatagramPacket - Java examples - Java programs

Constructors of DatagramPacket class

  • DatagramPacket(byte[] barr, int length): it creates a datagram packet.It is used to receive the packets.
  • DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet.It is used to send the packets.

Sending DatagramPacket by DatagramSocket

//DSender.java  
import java.net.*;  
public class DSender{  
  public static void main(String[] args) throws Exception {  
    DatagramSocket ds = new DatagramSocket();  
    String str = "Welcome to wikitechy java tutorial";  
    InetAddress ip = InetAddress.getByName("192.168.1.1");  
     
    DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);  
    ds.send(dp);  
    ds.close();  
  }  
}  
click below button to copy the code. By - java tutorial - team

Receiving DatagramPacket by DatagramSocket

//DReceiver.java  
import java.net.*;  
public class DReceiver{  
  public static void main(String[] args) throws Exception {  
    DatagramSocket ds = new DatagramSocket(3000);  
    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();  
  }  
}  
click below button to copy the code. By - java tutorial - team

Related Searches to DatagramSocket | java DatagramSocket | DatagramPacket