Java Socket Programming Using UDP

As we discussed earlier , the transport layer has two protocols: TCP and UDP.We can use either TCP or UDP in our application.java provides options to select either TCP or UDP in applications.This chapter describes Java Socket programming using UDP with example.

Java Socket programming using UDP

A comparison between  TCP and UDP is given below as a table.

SL.No: TCP UDP
1 TCP is connection oriented Connection less
2 Reliable Un-reliable
3 TCP is slower when compared with UDP Faster
4 TCP header size is 20 bytes UDP header size is 8 bytes
5 Flow control is there No flow control

Java Socket Programming with UDP-example

So , from the above discussion it is clear that UDP is connection less and less reliable protocol.But it is faster when comparing with TCP.In this chapter , we are  discussing how to use UDP in our applications with a suitable example.

In ithis example we have two Java classes.One class acts as client  and the other is the server.Let us see the server code first.

UDPSocketServer.java

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPSocketServer {
DatagramSocket socket = null;

public UDPSocketServer() {

}

public void createAndListenSocket() {
try {
socket = new DatagramSocket(9876);
byte[] incomingData = new byte[1024];

while (true) {
DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length);
socket.receive(incomingPacket);
String message = new String(incomingPacket.getData());
System.out.println("Received message from client: " + message);
InetAddress IPAddress = incomingPacket.getAddress();
int port = incomingPacket.getPort();
String reply = "Thank you for the message";
byte[] data = reply.getBytes();
DatagramPacket replyPacket =
new DatagramPacket(data, data.length, IPAddress, port);
socket.send(replyPacket);
Thread.sleep(2000);
socket.close();
}

} catch (SocketException e) {
e.printStackTrace();
} catch (IOException i) {
i.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
UDPSocketServer server = new UDPSocketServer();
server.createAndListenSocket();
}
}

In the above code , we are just initializing a DataGramSocket on port  9876.It is waiting to get data from anywhere from the network.Once it receives a message it is displaying in the console and sending a reponse. Then closing the socket(Just to exit the application)

Now lets see the client code.

UDPSocketClient

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

public class UDPSocketClient {
DatagramSocket Socket;

public UDPSocketClient() {

}

public void createAndListenSocket() {
try {

Socket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] incomingData = new byte[1024];
String sentence = "This is a message from client";
byte[] data = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(data, data.length, IPAddress, 9876);
Socket.send(sendPacket);
System.out.println("Message sent from client");
DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length);
Socket.receive(incomingPacket);
String response = new String(incomingPacket.getData());
System.out.println("Response from server:" + response);
Socket.close();

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
UDPSocketClient client = new UDPSocketClient();
client.createAndListenSocket();
}
}

The client first creates a DataGramSocket .Then creating a DataGramPacket with local host as the destination ip address.Then sending the packet.It is waiting for  getting the response from network.Then closing the socket.

Now to see the output,just run the two classes.Output will be displayed in two consoles.In our example , we used local  host as the destination address.If we need to  make communication between two machines , then in the client ,it is possible to change the ip address of  destination.

See related topics:

Overview to networking with Java

TCP communication in Java