Simple Calculator via UDP in Java
Last Updated :
07 Jan, 2022
Networking is two-way communication between a host and a server, rather than an exchange of information. Any server is set up to respond to specific queries as requested by a client. There are many different kinds of servers based on the utility they provide to the users. Some examples include File Server, Application Server, Domain Server, etc.
Let’s take an example to demonstrate how a request by any client is handled in the client-server model of communication. Assume that there is a company X that has hundreds of employees each working on their own system and most of them use the printer to print some report or invoice etc. Installing printers on every system is not a very economical solution to the problem of providing printing facilities to the users. An alternative to this is to set up a Print Server and install a printer on that system. When an employee wants to print something, he or she can send a request to the server asking to reserve the printer for him/her. The server on receiving the request has t Client-Side Programming make a decision based on many factors like availability of printer, rate of incoming requests, etc, and finally, respond to the request telling the client about the status of printer. One fundamental aspect of any server is that it should be specific, not generic. It must not generate a similar response to every request rather respond based on the nature of the request, the client to which it is responding, etc.
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.
Let first discuss client-side programming followed by server-side programming. Starting off with the client-side programming as follows:
A. Client Side Programming
For sending or receiving over the Internet, there is a need to know the socket address of the listening entity, that is IP address and port number of the listener. Generally, the client knows, or server relays the socket address to which it is listening. So on the client side, there is very little change in the code part.
Instead of invoking only a send() call, the client also invokes receive() call. Rest all steps remain the same.
Steps involved are as follows:
- 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.
- 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
- Invoke a send() call on socket object: This would send our request carrying the equation to the server for processing.
- 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.
Example 1
Java
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 ;
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();
DatagramPacket DpSend = new DatagramPacket(
buf, buf.length, ip, 1234 );
ds.send(DpSend);
if (inp.equals( "bye" ))
break ;
buf = new byte [ 65535 ];
DatagramPacket DpReceive
= new DatagramPacket(buf, buf.length);
ds.receive(DpReceive);
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:
- Establish a socket connection.
- 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.
- 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 connection to avoid any memory leakage issue.
Example
Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.StringTokenizer;
class GFG {
public static void main(String[] args)
throws IOException
{
DatagramSocket ds = new DatagramSocket( 1234 );
byte [] buf = null ;
DatagramPacket DpReceive = null ;
DatagramPacket DpSend = null ;
while ( true ) {
buf = new byte [ 65535 ];
DpReceive = new DatagramPacket(buf, buf.length);
ds.receive(DpReceive);
String inp = new String(buf, 0 , buf.length);
inp = inp.trim();
System.out.println( "Equation Received:- "
+ inp);
if (inp.equals( "bye" )) {
System.out.println(
"Client sent bye.....EXITING" );
break ;
}
int result;
StringTokenizer st = new StringTokenizer(inp);
int oprnd1 = Integer.parseInt(st.nextToken());
String operation = st.nextToken();
int oprnd2 = Integer.parseInt(st.nextToken());
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);
buf = res.getBytes();
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...