The Role Of Datagram In Java Networking

Introduction

Datagram is a type of packet that represents an entire communication. There is no necessity to have a connection/disconnection stages when communicating using datagrams. There are two classes in Java that enable communication using datagrams. 

  • DatagramPacket is the class that acts as a data container.
  • DatagramSocket is a mechanism used to send or receive DatagramPackets

A DatagramPacket object can be created as follows:

DatagramPacket(byte data[], int size)

The above constructor takes the byte array and its size as its parameter.

DatagramPacket(byte data[], int size, InetAddress I, int port)

In addition to the byte array and its size, the above constructor takes the InetAddress and the port as its parameters.

DatagramSocket

The class DatagramPacket does not provide methods to send or receive data. This job is taken up by the DatagramSocket class.

Constructor Used

Creating a DatagramSocket object throws a SocketException, which must be handled. Two constructors of DatagramSocket class. The first constructor does not take any parameters and is created as follows:

DatagramSocket s=new DatagramSocket();

The next constructor is given as follows:

DatagramSocket s=new DatagramSocket(int port);

Methods Used

  • send(DatagramPacket d) - to dispatch the given DatagramPacket object.
  • receive(DatagramPacket p) - to receive the given DatagramPacket object.
  • close(), closes the socket connection.

Consider the example containing a program code for a client and server using Datagram. Any string entered as input in the window running the servers program is displayed in the client’s window. The user has to enter “End” to exit the server program and press ctrl+c to exit the client program.

Note that the client and the server program should run on the same machine. Open two instances of the MS-DOS prompt a simultaneously run both programs.

Source Code

import java.net.*;
import java.io.*;
class DatagramClient {
    public static DatagramSocket ds;
    public static byte buffer[] = new byte[1024];
    public static int clientport = 789, serverport = 790;
    public static void main(String args[]) throws Exception {
        ds = new DatagramSocket(clientport);
        System.out.println("Client is waiting for server to send data");
        System.out.println("Press Ctrl+C to Dos Prompt");
        while (true) {
            DatagramPacket p = new DatagramPacket(buffer, buffer.length);
            ds.receive(p);
            String psr = new String(p.getData(), p.getLength());
            System.out.println(psr);
        }
    }
}

Output

The Role of Datagram in Java Networking

The client program creates a DatagramSocket at the clientport, say 789, and a serverport, say 790. The creation of the DatagramSocket object throws an exception, which has to be caught; throws Exception phrase is used at this junction. The socket created with 789 as the port number waits for the server to send input. The DatagramPacket object stores the information in packets obtained from the receive method. This information is converted to a string and displayed.

Open another new file in the editor and type the following code

import java.net.*;
import java.io.*;
class DatagramServer {
    public static DatagramSocket ds;
    public static int clientport = 789, serverport = 790;
    public static void main(String args[]) throws Exception {
        byte buffer[] = new byte[1024];
        ds = new DatagramSocket(serverport);
        BufferedReader dis = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Server Waiting for Input");
        InetAddress ia = InetAddress.getByName("localhost");
        while (true) {
            String str = dis.readLine();
            if ((str == null || str.equals("end"))) break;
            buffer = str.getBytes();
            ds.send(new DatagramPacket(buffer, str.length(), ia, clientport));
        }
    }
}
  • Save the file as DatagramServer.java
  • Open another instance of MS-DOS prompt
  • Compile the file using javac DatagramServer.java in that instance.
  • Run the file using java DatagramServer

Output appears as,

The Role of Datagram in Java Networking

When we press the Enter key after each line, the line appears on the client side. This program demonstrates a server using Datagram.

Note that the same clientport and serverport are used. The InetAddress of the local machine is obtained. A DatagramPacket object is created using this InetAddress and the clientport. The object thus created is dispatched to the client using the send method.

Summary

An entire communication is represented by a datagram. Datagrampacket is the class, which acts as the data container, and DatagramSocket is a mechanism used to send or receive Datagrampackets.