A datagram socket is used to send and receive datagram packets. A DatagramSocket object is a local connection to a port that does the sending and receiving. There is no distinction between a UDP socket and a UDP server socket. Also unlike TCP sockets, a DatagramSocket can send to multiple, different addresses. The address to which data goes is stored in the packet, not in the socket. Some applications that you write to communicate over the network will not require the reliable, point-to-point channel provided by TCP. Rather, your applications might benefit from a mode of communication that delivers independent packages of information. The DatagramPacket and DatagramSocket classes in the java.net package implement system-independent datagram communication using UDP. A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.

Java’s support for UDP is contained in two classes:

java.net.DatagramSocket:

It is used for receiving data packets. Following are the constructors of this class.

  • public DatagramSocket() throws SocketException
  • public DatagramSocket(int port) throws SocketException
  • public DatagramSocket(int port, InetAddress laddr) throws SocketException

java.net.DatagramPacket:

It is used for creating and sending data packets.

  • public DatagramPacket(byte[] data, int length)
  • public DatagramPacket(byte[] data, int length, InetAddress iaddr, int iport)

Example-1

In this example, wrapper for an array of bytes from which data will be sent or into which data will be received also contains the address and port to which the packet will be sent.

String s = "My first UDP Packet"
byte[] b = s.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length);

Example -2

try {
	 InetAddress uni = new InetAddess("sourcecodemania.com");
 	int num = 4321;
 	String s = "My second UDP Packet"
	 byte[] b = s.getBytes();
 DatagramPacket dp = new DatagramPacket(b, b.length, uni, num);
}
catch (UnknownHostException e) {
System.err.println(e);
}

Sending a Datagram Packet

To send data to a particular server:

  1. Convert the data into byte array
  2. Pass this byte array, the length of the data in the array (most of the time this will be the length of the array) and the InetAddress and port to which you wish to send it into the DatagramPacket() constructor.
  3. Next create a DatagramSocket and pass the packet to its send() method

Example: Sending a packet

InetAddress uni= new InetAddess("sourcecodemania.com");
int num = 4321;
String s = "My second UDP Packet";
byte[] b = s.getBytes();
DatagramPacket  dp = new DatagramPacket(b, b.length, uni, num);
DatagramSocket  sender = new DatagramSocket();
sender.send(dp);

Receiving UDP Datagrams

To receive UDP datagram packet:

  1. Construct a DatagramSocket object on the port on which you want to listen.
  2. Pass an empty DatagramPacket object to the DatagramSocket’s receive() method.
    • public synchronized void receive(DatagramPacket dp) throws IOException
  3. The calling thread blocks until a datagram is received.
  4. dp is filled with the data from that datagram.
  5. Use getPort() and getAddress() to tell where the packet came from,
  6. getData() to retrieve the data, and getLength() to see how many bytes were in the data.
  7. If the received packet was too long for the buffer, it’s truncated to the length of the buffer.
  8. Length is reset when packet is received

Example: Receiving UDP Datagrams

try {
 byte buffer = new byte[65536];
 DatagramPacket  incoming = new DatagramPacket(buffer, buffer.length);
 DatagramSocket  ds = new DatagramSocket(4321);
ds.receive(incoming);
byte[] data = incoming.getData();
 String s = new String(data, 0, data.getLength());
System.out.println("Port" + incoming.getPort() + " on " + incoming.getAddress() + " sent this message:");
System.out.println(s);
}
 catch (IOException e) {
	System.err.println(e); }
class netFunctions {
  public static void main (String args[]) {
    try {
     InetAddress address = InetAddress.getByName("sourcecodemania.com");
        System.out.println(address);
     InetAddress addlocal= InetAddress.getLocalHost();
        System.out.println(addlocal);
     InetAddress localname = InetAddress.getLocalHost();
          System.out.println("Hello. My name is " +  localname.getHostName());
    }
    catch (UnknownHostException e) {
   	   System.out.println("Could not find site");
    }
  }
}

OUTPUT:

       www.sourcecodemania.com/115.186.131.73
       sourcecodemania-dcefc1406/10.3.60.36
       Hello. My name is sourcecodemania-dcefc1406

Stream Socket vs. Datagram Socket

Click here to read comparison of Stream Socket and Datagram Socket and also a Client-Server programming example.

Related Posts

Tagged with: ClassesJAVAObject OrientedProgrammingSource Code
 

4 Responses to UDP Datagram Sockets in Java

  1. Sameer Jain says:

    how to use Japplet in this particular example

  2. Martin Meys says:

    Thanks for this great article, it helps me a lot!

    However, I noticed a little mistake : in the example “Receiving UDP Datagrams”, at line 7, it is “incoming.getLength()” and not “data.getLength()”

  3. Anonymous says:

    Thank you for the help.Now I understood how UDP works

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds