Simple Calculator via UDP in Java
This article is the implementation of a simple calculator-server via UDP
wherein the client will send the mathematical equation to the server and
the server will respond with the answer to the equation.
A. Client Side Programming : Steps involved are as follows:
1. Creation of DatagramSocket: First, a datagramSocket object is created
to carry the packet to the destination and to receive it whenever the
server sends any data.
2. Creation of DatagramPacket: In this step, the packet for
sending/receiving data via a datagramSocket is created.
Note : There is a difference in constructors for creating a datagram
packet for sending and receiving the data
3. Invoke a send() call on socket object: This would send our request
carrying the equation to the server for processing.
4. Invoke a receive() call on socket object: This is used to receive the
data sent by the server after processing our request. This would freeze
our program until the server responds or throws an error if it takes too
much time.
// Java Program to illustrate Client Side implementation
// of Simple Calculator using UDP
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class GFG {
public static void main(String args[]) throws IOException
Scanner sc = new Scanner(System.in);
DatagramSocket ds = new DatagramSocket();
InetAddress ip = InetAddress.getLocalHost();
byte buf[] = null;
// loop while user not enters "bye"
while (true)
System.out.print( "Enter the equation in the format:");
System.out.println("'operand1 operator operand2'");
String inp = sc.nextLine();
buf = new byte[65535];
buf = inp.getBytes();
// Step 2
// Creating the datagramPacket for sending the
// data.
DatagramPacket DpSend = new DatagramPacket(
buf, buf.length, ip, 1234);
// Invoking the send call to actually send the
// data.
ds.send(DpSend);
// Break the loop if user enters "bye"
// using the break keyword
if (inp.equals("bye"))
break;
buf = new byte[65535];
// Creating an object of DatagramPacket class
DatagramPacket DpReceive
= new DatagramPacket(buf, buf.length);
ds.receive(DpReceive);
// Print and display command
System.out.println(
"Answer = "
+ new String(buf, 0, buf.length));
Output:
Enter the equation in the form: 'operand operator operand'
5*6
Answer=30
Enter the equation in the form: 'operand operator operand'
5+6
Answer=11
Enter the equation in the form: 'operand operator operand'
9/3
Answer=3
B. Server Side Programming
As the socket address is required to communicate over the internet, the
server must know the address through which the client is sending the
request. Let us look step by step how server handles the problem of port
number and respond to the queries of the client.
Steps involved on client side are as follows:
1. Establish a socket connection.
2. Process the equations coming from client: In server side also we
open both the inputStream and outputStream. After receiving the
equation, we process it save the result to be sent back to the client.
3. Creating a packet for sending the result : This step creates a problem
for the server as it does’nt know the port number of the client. To get the
port, we use the following method of DatagramPacket class.
public int getPort()
Syntax:
public int getPort()
Returns the port number to which the specified datagram packet is being
sent to or
from which the packet is received.
Note: Lastly do remember to close the conn
// Java Program Illustrating Server Side Implementation
// of Simple Calculator using UDP
// Importing required classes
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.StringTokenizer;
// Main class
// Calc_Server_UDP
class GFG {
// MAin driver method
public static void main(String[] args)
throws IOException
// Creating a socket to listen at port 1234
DatagramSocket ds = new DatagramSocket(1234);
byte[] buf = null;
// Initializing them initially with null
DatagramPacket DpReceive = null;
DatagramPacket DpSend = null;
while (true) {
buf = new byte[65535];
// Creating a DatagramPacket to receive the data.
DpReceive = new DatagramPacket(buf, buf.length);
// Receiving the data in byte buffer.
ds.receive(DpReceive);
String inp = new String(buf, 0, buf.length);
// Using trim() method to
// remove extra spaces.
inp = inp.trim();
System.out.println("Equation Received:- "
+ inp);
// Exit the server if the client sends "bye"
if (inp.equals("bye")) {
System.out.println(
"Client sent bye.....EXITING");
// Exit from program here itself without
// checking further
break;
int result;
// Use StringTokenizer to break the
// equation into operand and operation
StringTokenizer st = new StringTokenizer(inp);
int oprnd1 = Integer.parseInt(st.nextToken());
String operation = st.nextToken();
int oprnd2 = Integer.parseInt(st.nextToken());
// Perform the required operation
if (operation.equals("+"))
result = oprnd1 + oprnd2;
else if (operation.equals("-"))
result = oprnd1 - oprnd2;
else if (operation.equals("*"))
result = oprnd1 * oprnd2;
else
result = oprnd1 / oprnd2;
System.out.println("Sending the result...");
String res = Integer.toString(result);
// Clearing the buffer after every message
buf = res.getBytes();
// Getting the port of client
int port = DpReceive.getPort();
DpSend = new DatagramPacket(
buf, buf.length, InetAddress.getLocalHost(),
port);
ds.send(DpSend);
Output:
Equation received:-5 * 6
Sending the result...
Equation received:-5 + 6
Sending the result...
Equation received:-9 / 3
Sending the result...
Note: In order to test the above programs on the system, please make sure
that you run the server program first and then the client one. Make sure you
are in the client console and from there enter the equation in the
format-“operand1 operator operand2” and press Enter. Answer to the
requested equation will be shown in the client console only. Finally to
terminate the communication, type “bye” (without quotes) and hit enter.
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks
and would like to contribute, you can also write an article
using write.geeksforgeeks.org or mail your article to review-
[email protected]. See you