Simple Calculator Via UDP in Java
Simple Calculator Via UDP in Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class GFG {
InetAddress ip = InetAddress.getLocalHost();
while (true)
buf = inp.getBytes();
// Step 2
// data.
// data.
ds.send(DpSend);
if (inp.equals("bye"))
break;
DatagramPacket DpReceive
ds.receive(DpReceive);
System.out.println(
"Answer = "
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
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 {
throws IOException
ds.receive(DpReceive);
inp = inp.trim();
+ inp);
if (inp.equals("bye")) {
System.out.println(
// checking further
break;
int result;
if (operation.equals("+"))
else if (operation.equals("*"))
else
buf = res.getBytes();
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.