If you are familiar with basic networking protocols like TCP and UDP , you already might know TCP is reliable and used in most cases, specially 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, intra-net/private network communication where data/packet loss risk is minimal. Thus even being unreliable, its making our life lot easier where some failures can be tolerated and fast communication 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 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 connection less protocol. That means, it will create a packet and just sent to server without making any connection in prior. Lets look at the following code example:
atagramSocket 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(); }A you can see above, we are creating a ‘DatagramPacket’ object and sent it to our destination host/port via a ‘DatagramSocket’
object and finally close the socket.When you have your components and also the hosting server operating, you will certainly wish to setup your server. This need to start as a computerized system and may then become personalized based upon your necessities. You will would like to make certain that you recognize what you really want the hosting server to be capable to perform prior to you make the effort to identify how you are going to go about doing it. Learn more about wordpress hosting at the link.
Basic UDP Server:
On the server-side, which will be receiving the request, will need to keep its specific port open where clients will be sending data and whenever a data packet comes, it receive it, process it, send response and wait for the next request. So, there is two thing, we should be careful in server-side implementation:
- Server should always be listening: We need to make sure that, 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 request and sending response. If you intend to do some other tasks in parallel, you should consider moving this part into a thread implementation.
Lets 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(); } }As you can, the same datagram packet we sent from client, is used to receive the request to keep consistency of data inside the packet and then convert the data to string, which you can check further to know what kind of request it is and then reply back a friendly response. As mentioned earlier, the whole block is inside a while(true) loop so that it always wait and process data as it comes.
UDP MultiCast Communication:
Sometimes in a network, you will may want to send a UDP packets to a set of processes in a network instead of just one. In such cases, sending separately to each of them isn’t neither efficient nor scalable. Thus, as a better solution, java provides support for ‘MulticastSocket’ , which can be used to send message to a multi-cast I/port pair, for the group of processes in the network and all those processes will be listen to those IP/port to see if a new message arrives.
the client side implementation for java multi-cast communication is exactly same as general UDP, only the socket instance will be of 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"));And you should now good to go to receive packets which are broadcasted to that IP/port pair.
Looking for some ready-made wrapper class?
For my masters course project purpose, I had to create few classes for generalize the UDP communication. If you are just 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:
Hope this small tutorial will help you understand/getting 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 🙂
Thanks Rana for the writeup and the code. Quite useful.