Datagrams in java

Datagrams are bundles of information passed between machines.

  Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to catch it.

  For implementing Datagrams concept of Connection-less communication Java provides two classes :

  1) DatagramSocket
2 ) DatagramPacket

  DatagramPacket object is the data container. It represents packet that contain data part which is transferred from one computer to another computer.
DatagramSocket is the mechanism used to send or receive the DatagramPackets.


DatagramPacket Class

This class provides facility for connection less transfer of messages from one system to another. Each message is routed only on the basis of information contained within the packet and it may be possible for different packets to route differently. There is also no guarantee as to whether the message will be delivered or not, and they may also arrive out of order. This class provides mechanisms for creation of datagram packets for connectionless delivery using datagram socket class.

For sending purpose, following constructors are used :

1) Syntax :
public DatagramPacket(byte[] buf,
              int offset,
              int length,
              InetAddress address,
              int port)
Parameters :
buf : byte array
offset : offset into the array
length : length of message to deliver
address : address of destination
port : port number of destination


2) Syntax :
public DatagramPacket(byte[] buf,
              int offset,
              int length,
              SocketAddress address)
Parameters :
buf : byte array
offset : offset into the array
length : length of message to deliver
address : socket address of destination

3) Syntax :
public DatagramPacket(byte[] buf,
              int length,
              InetAddress address,
              int port)
Parameters :
buf : byte array
length : length of message to deliver
address : address of destination
port : port number of destination

For receiving purpose, following constructors are used :


1)    Syntax :public DatagramPacket(byte[] buf, int offset, int length)
    Parameters :
    buf : byte array
    offset : offset into the array
    length : length of message to deliver

    2) Syntax :public DatagramPacket(byte[] buf , int length)
    Parameters :
    buf : byte array
    length : length of message to deliver

Methods of DatagramPacket Class

Commonly used methods of datagram packet class

Method Description
public InetAddress getAddress() Returns the IP address to which this packet is sent to or from which it was received
public int getPort() Returns the port to which this packet is sent to or from which it was received. This method is specifically used on the server from getting the port of the client who sent the request.
public byte[] getData() Returns the data contained in this packet as a byte array. The data starts from the offset specified and is of length specified.
public int getOffset() Returns the offset specified.
public int getLength() Returns the length of the data to send or receive
public void setData(byte[] buf, int offset, int length) Used to set the data of this packet.

DatagramSocket Class

DatagramSocket class in java provides functionality for sending and receiving the packet. Every packet sent from a datagram socket is individually routed and delivered . It follow UDP Protocal . A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.

Commonly used Constructors of DatagramSocket class


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

Methods of DatagramSocket Class

Commonly used methods are

Method Description
public void send(DatagramPacket p) Sends a datagram packet from this socket.
public void receive(DatagramPacket p) It is used to receive the packet from a sender.
public void bind(SocketAddress addr) Binds this socket to specified address and port number.

Sender for sending packet



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

public class Sender {
	public static void main(String[] args) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

			System.out.println("Enter the content to be send: ");

			String content = br.readLine();

			// Create the packet to be send using DatagramPacket
			DatagramPacket packet = new DatagramPacket(content.getBytes(), content.getBytes().length,
					InetAddress.getLocalHost(), 8888);

			// now create socket using DatagramSocket to send the data..
			DatagramSocket socket = new DatagramSocket();

			// now send the packet using socket

			socket.send(packet);
			System.out.println("packet is sent successfully...");


		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
Enter the content to be send: 
onlyjavatech
packet is sent successfully...

Receiver for receiving packet


import java.net.*;

public class Receiver {
	public static void main(String[] args) {
		try {
			// create a empty packet to receive the data

			byte b[] = new byte[10000];

			DatagramPacket p = new DatagramPacket(b, b.length);

			DatagramSocket socket = new DatagramSocket(8888);
			System.out.println("waiting for the packet.....");

                        //receiving packet
			socket.receive(p);

			System.out.println(new String(b));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}
}
waiting for the packet.....
onlyjavatech