Working with UDP in Java networking-the Datagram socket and packets


DatagramSocket and DatagramPacket are classes we use in Java to work with the UDP protocol. the classes are found in the java.net package. The UDP is a non reliable protocol as it does not goes with the point to point handshake. This protocol rely on the IP to transmit data successfully.

The UDP is one of the transporting protocol which is used to transfer the data. When we work with the UDP there is pro as well as con. The pro is that It does not requires to handshake the other party before transmitting the data however that data may get lost in between it the con. Then The UDP does not uses the Socket and server socket, instead it uses the DatagramSocket and DatagramPacket.

The communication steps are as follows:

 

For Server Class:
1. create a Datagram Socket which will operate on a particular port.
2. Now create a byte array which will contain the data received or to be send.
3. Now a datagram Packet is needed which will use the byte array as the data to create a packet. Now the point to be noticed is that when receiving the data you only need to specify the byte array but while sending you must specify the InetAddress and port to which the packet is to be transmitted, this is because the UDP packed rely on the IP to complete its transmission as there is no Point to point connection operating.
4. send or receive the data.
5. In case you are receiving the data this will be in the byte array associated with the packet, so you will need to retrieve it from that DatagramPacket using method getData() which will return a byte array which in turn can be converted into string easily.

So these five steps takes you through the whole concept of data transmission using UDP, using Java networking concepts. So now let us look at the program which will depict these five steps in the form of code.

The logic of the program is to set up communication between the client and server, the client will send a message to server and server will sent back acknowledgement.

Note: in actual UDP communication there is no acknowledgement, in the program it is just to make a logic to understand the concept.


package networking;
import java.io.*;
import java.net.*;
public class DGServer {
    public static void main(String[] args) throws Exception{
        DatagramSocket ds = new DatagramSocket(5000);
        System.out.println("Datagram Socket initialized");
        byte[] bb = new byte[128];
        DatagramPacket dp = new DatagramPacket(bb, bb.length);
        System.out.println("Packet created");
        System.out.println("Waiting for data from client");
        ds.receive(dp);
        System.out.println("Data Received");
        String s = new String(dp.getData());
        System.out.println(s);
        byte[] b = ("Data Acknowledged:"+s).getBytes();
        System.out.println("Sending back acknowledge to client");
        ds.send(new DatagramPacket(b,b.length,dp.getAddress(),dp.getPort()));
        System.out.println("Acknowledgement sent");
    }
}

This is datagram server class which incorporate many printings to show the program proceedings at each step. We are using the port 5000, to communicate. This program creates a DatagramSocket at port 5000 and the byte array bb will endure the data received. We have bind this array with the DatagramPacket as you will see only the name and size of array has been passed however you may also specify the index from where to start. Please check the Class definition for more details on constructor.

After creating the packet we are receiving the data in that packet awaiting on the socket. DatagramSocket provide the method send() and receive() which takes the DatagramPacket as the argument. This will take on the packet and will have it in the byte array bounded with the DatagramPacket. To send the acknowledgement back to the client we have used the same phenomenon except that now we need the address and port number on which client is communicating so we take it form the Socket object on which client contacted the server.

This address and the port number is passed on the the Packet we need to send back to the client. rest of the procedure is same. Just to save some precious reference variables we have used method chaining and the wrapping but we hope you are familiar with Java to understand these little concepts.

Here is the client class and the results. the results are shown in the three steps.


package networking;
import java.io.*;
import java.net.*;

public class DGClient {
    public static void main(String[] args) throws Exception{
        DatagramSocket ds = new DatagramSocket();
        byte[] b = {'h','e','l','l','o',' ','w','o','r','l','d'};
        ds.send(new DatagramPacket(b,b.length,InetAddress.getLocalHost(),5000));
        byte[] ack = new byte[128];
        DatagramPacket dp = new DatagramPacket(ack,ack.length,InetAddress.getLocalHost(),5000);
        ds.receive(dp);
        String s = new String(dp.getData());
        System.out.println(s);
    }
}

The client program creates the DatagramSocket without the port number because it will communicate the packet using the Address and port in the packet. As you see in the program the packet both the sending and receiving specifies the address and port number however if you will compare it to the server you will find that when you receive the packet at sever it does not need the port or InetAddress, so that makes the difference.

Run the program Step 1: run the server

Datagram Socket initialized
Packet created
Waiting for data from client

Step 2: run the client

Data Acknowledged:hello world

step 3: check back the changes in the server output

Datagram Socket initialized
Packet created
Waiting for data from client
Data Received
hello world
Sending back acknowledge to client
Acknowledgement sent

Note: That port 0 to 1023 are already reserved to some standard services and uses, so you can use anything above this, taking in account that any other service is not using that port on the same host.

How to Run The programs:

As you see there are two different classes and you have to run these both simultaneously to check the working, so here is what you need to do.

Running from the command line:
1. you will need to run two different command terminals.
2. first track down the location of the server file and compile and run it.
3. Now, without closing the server terminal, go to the other terminal and track down and run the client program.
4. Now you can check the result and working of these two programs together.

Running from IDE:
1. Running from IDE is easier than running from command line.
2. First right click the server file and run it, the IDE will output the result on the console.
3. Now do the same with the client file and the IDE will open another console to show the result.
4. You can switch through the the consoles to check the result.