If you are familiar with basic networking protocols like TCP and UDP , you already might know TCP is reliable and used in most cases, especially for corruption-file download/requests over HTTP, email communications etc. However, some other large part is still considered better with UDP communications like multi-player game programming, live video streaming, and intra-net/private network communication where data/packet loss risk is minimal. Thus, even being unreliable makes our life a lot easier where some failures can be tolerated and fast communication is required.
In this tutorial, which is intended for complete beginners, we will see, how we can do some basic UDP programming in Java on both client and server-side implementation and introduce you to a small Java library, that I wrote a few days ago because of my university study purpose, which you may consider to reuse.
Basic UDP Client In JAVA:
To memorize the mechanism easily, you should understand the concept clearly. UDP is a connectionless protocol. That means it will create a packet and just send it to the server without making any connection prior. Let’s look at the following code example:
DatagramSocket socket;
try{
socket = new DatagramSocket();
String requestData = "'Hello World' via UDP in JAVA";
byte [] m = requestData.getBytes();
InetAddress aHost = InetAddress.getByName("myhostname");
int serverPort = 1234;
DatagramPacket request = new DatagramPacket(m, requestData.length(), aHost, serverPort);
socket.send(request);
byte [] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
socket.setSoTimeout(2000);
this.socket.receive(reply);
}
catch(SocketTimeoutException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}finally{
socket.close();
}
Code language: JavaScript (javascript)
As you can see above, we are creating a ‘DatagramPacket’ object and sending it to our destination host/port via a ‘DatagramSocket’
object and finally close the socket.
Basic UDP Server:
On the server side, which will be receiving the request, it will need to keep its specific port open where clients will be sending data and whenever a data packet comes, it receives it, processes it, sends a response and waits for the next request. So, there are two things, we should be careful of in server-side implementation:
- The server should always be listening: We need to make sure that, the server will be listening on the specified port always, in a never-ending loop. so a ‘while(true)’ loop is necessary here.
- This program will always be doing only this task: This piece of code will only be responsible for doing this task of receiving requests and sending responses. If you intend to do some other tasks in parallel, you should consider moving this part into a thread implementation.
Let’s look at the following Java code example for the UDP server:
DatagramSocket socket;
DatagramPacket request;
while(true)
{
String data = null;
try {
buffer = new byte[this.DGRAM_LENGTH];
request = new DatagramPacket(buffer, buffer.length);
socket.receive(this.request);
data = new String(this.request.getData());
String request = data.trim();
//do your processing with request data
//Sending response
String response = "Test Reply from UDP server!";
DatagramPacket reply = new DatagramPacket(response.getBytes(), response.length(), request.getAddress(), request.getPort());
this.socket.send(reply);
}
catch(Exception err) {
err.printStackTrace();
}
}
Code language: JavaScript (javascript)
As you can see, the same datagram packet we sent from the client, is used to receive the request to keep the consistency of data inside the packet and then convert the data to a string, which you can check further to know what kind of request it is and then reply a friendly response. As mentioned earlier, the whole block is inside a while(true) loop so that it always waits and processes data as it comes.
UDP MultiCast Communication:
Sometimes in a network, you will want to send a UDP packet to a set of processes a network instead of just one. In such cases, sending separately to each of them is neither efficient nor scalable. Thus, as a better solution, java provides support for ‘MulticastSocket’, which can be used to send messages to a multi-cast I/port pair, for the group of processes in the network and all those processes will listen to those IP/port to see if a new message arrives.
the client-side implementation for Java multi-cast communication is the same as general UDP, only the socket instance will be of the MulticastSocket class.
On the other hand, for server-side implementation, one extra step will be to join the multicast group as below:
socket.joinGroup(InetAddress.getByName("hostname"));
Code language: CSS (css)
And you should now be good to go to receive packets which are broadcasted to that IP/port pair.
Looking for a ready-made wrapper class?
For the purpose of my master’s course project, I had to create a few classes to generalize UDP communication. If you are starting out with UDP, you can try reusing those, which might help you get to a quick starting point.
GitHub Repository: JAVA UDP wrapper library
It’s written as an Eclipse project, so if you are using Eclipse, you can directly import it.
The codes are written in rush and doesn’t have much standards/best practices followed. Sorry about that, will try make them better sometime. Also, those are just used in course projects with limited tests, so could be error prone, use at your own risk.
Final Words:
I hope this small tutorial will help you understand/get started with UDP programming in java a little more easily. If you have any confusion/questions about any part, please ask via commenting here. Happy coding 🙂
Thomas Lee S says
Thanks Rana for the writeup and the code. Quite useful.