
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Simple Calculator via UDP in Java
To enable communication between devices over the Internet, we use Internet Protocol suite. The UDP is one of the protocols of this suite and its full form is User Datagram Protocol. Unlike TCP, it is not reliable and also it is a connection less protocol. It does not establish any kind of connection to other devices before sending the data.
In this article, we will develop a simple client-server side calculator using UDP in Java. The client will request the operation and the server will send the result to client device after calculating it. But first, let's briefly understand a few basic concepts first about Java networking.
InetAddress
An IP address is either a 32-bit or 128-bit unsigned number that uniquely identifies devices on Internet. It is easy to remember the name of IP host rather than the numerical address. So, we need to encapsulate this using InetAddress class. We use its built-in method getLcalHost() to retrieve the IP address of LocalHost.
Datagrams
They are small-sized packets that contain data that can be passed between two machines over the internet. Java implements two classes to establish UDP connection:
-
DatagramSocket class: It is used to send and receive datagram packets. It also determines the destination of these packets. Its built-in methods send() and receive() are used to send and receive the packets respectively.
-
DatagramPacket class: Its object stores the data to be sent.
Java Program of Calculator using UDP
We will write two separate program for client-side and server-side for the calculator:
Client Side Code
Follow the steps to write code for the client-side:
-
First import the java.net package to access all the classes regarding Java networking and java.io for input and output streams. The java.util package to use Scanner class.
-
Make a UDP connection and then, fetch the LocalHost address.
-
Now, inside the try block, we will ask for user input to request an operation and to receive the result accordingly. It will be done by send() and receive() methods of DatagramSocket class.
Program: Client-Side
The client-side code is as follows:
import java.io.*; import java.net.*; import java.util.*; public class ClientCalc { public static void main(String args[]) throws IOException { Scanner inp = new Scanner(System.in); // making UDP connection DatagramSocket datagsokt = new DatagramSocket(); // fetching the localhost address InetAddress addr = InetAddress.getLocalHost(); byte strm[] = null; try { while (true) { System.out.println("Type 1 for Addition"); System.out.println("Type 2 for Subtraction"); System.out.println("Type 3 for Multiplication"); System.out.println("Type 4 for Division"); System.out.println("Enter your choice: "); String oprtr = inp.nextLine(); // to convert the user choice to byte strm = new byte[256]; strm = oprtr.getBytes(); // creating datagram packet to send to server DatagramPacket packtsend = new DatagramPacket(strm, strm.length, addr, 6666); datagsokt.send(packtsend); // Type 0 for cut the connection if (oprtr.equals("0")) { break; } // to receive the result from server strm = new byte[256]; DatagramPacket packtrec = new DatagramPacket(strm, strm.length); datagsokt.receive(packtrec); // display the result System.out.println("Your Result for the given operation = " + new String(strm, 0, strm.length)); } } // to handle exception catch(Exception exp) { System.out.println(exp); } } }
Server Side Code
Now, let's see how to write the server-side code:
-
First, establish a connection with the client and define two objects of DatagramPacket class to send and receive the packet using send() and receive() methods of DatagramSocket class.
-
Inside the try block, we receive the request from client and then, using switch case we perform the operation and send the result to client device.
Program: Server-Side
The practical implementation of server-side code:
import java.io.*; import java.net.*; class ServerCalc { public static void main(String[] args) throws IOException { // making connection to client DatagramSocket datagsokt = new DatagramSocket(6666); byte[] strm = null; DatagramPacket packtrec = null; DatagramPacket packtsend = null; try { while (true) { strm = new byte[256]; // to receive the packet from client packtrec = new DatagramPacket(strm, strm.length); datagsokt.receive(packtrec); String oprtr = new String(strm, 0, strm.length); System.out.println("Client has requested for " + oprtr ); int data1 = 15; int data2 = 5; int tot = 0; char opt = oprtr.charAt(0); switch(opt) { case '1' : tot = data1 + data2; break; case '2' : tot = data1 - data2; break; case '3' : tot = data1 * data2; break; case '4' : tot = data1 / data2; break; default : break; } // Converting the string result to integer String res = Integer.toString(tot); // converting the integer to bytes strm = res.getBytes(); int port = packtrec.getPort(); // getting port number // sending final result in the form of datagram packet packtsend = new DatagramPacket(strm, strm.length, InetAddress.getLocalHost(), port); datagsokt.send(packtsend); } } // to handle exception catch(Exception exp) { System.out.println(exp); } } }
How to Run the Programs?
To run both programs, open two cmd simultaneously on your local machine. On first cmd interface, compile and run the server-side program and then on the other interface, execute the client-side program.
Output on Client side
D:\Java Programs>java ClientCalc Type 1 for Addition Type 2 for Subtraction Type 3 for Multiplication Type 4 for Division Enter your choice: 1 Your Result for the given operation = 20
Output on Server side
D:\Java Programs>java ServerCalc Client has requested for 1
When we enter 0 the connection will get terminated and program will stop its execution.
Conclusion
In this article, we have learned about a few essential concepts of Java networking. Also, we discussed server-side and client-side programs of a simple calculator using UDP. We discovered how we could establish a connection between client and server devices in Java.