Simple Calculator using TCP in Java
Last Updated :
28 Jun, 2021
Prerequisite:
Socket Programming in Java
Networking just doesn't conclude with a one-way communication between the client and server. For example consider a time telling server which listens to request of the clients and respond with the current time to the client. Real-time applications usually follow a request-response model for communication.
The client usually sends the request object to the server which after processing the request, sends the response back to the client. In simple terms, the client requests for a particular resource available on the server and server responds it resource if it can verify the request. For example, when enter is pressed after entering the desired url, a request is sent to corresponding server which then replies by sending the response in form of a webpage which the browsers are capable of displaying.
In this article, a simple calculator application is implemented wherein the client will send requests to server in form of simple arithmetic equations and server will respond back with the answer to the equation.
Client-Side Programming
The steps involved on client side are as follows-
- Open the socket connection
- Communication: In the communication part, there is a slight change. The difference with the previous article lies in the usage of both the input and output streams to send equations and receive the results to and from the server respectively. DataInputStream and DataOutputStream are used instead of basic InputStream and OutputStream to make it machine independent. Following constructors are used -
- public DataInputStream(InputStream in)
Syntax: public DataInputStream(InputStream in)
Parameters:
in - The underlying InputStream.
Creates a DataInputStream that uses the specified underlying InputStream.
- public DataOutputStream(InputStream in)
Syntax: public DataOutputStream(OutputStream out)
Parameters:
out - The underlying OutputStream.
Creates a DataOutputStream that uses the specified underlying OutputStream.
After creating the input and output streams, we use the readUTF and writeUTF of the created streams methods to receive and send the message respectively.
- public final String readUTF()
throws IOException
Reads the string encoded using UTF8 encoding.
Throws:
IOException - the stream has been closed and the contained input stream
does not support reading after close,
or another I/O error occurs
- public final String writeUTF()
throws IOException
Writes the string encoded using UTF8 encoding.
Throws:
IOException - the stream has been closed and the contained input stream
does not support reading after close,
or another I/O error occurs
- Closing the connection.
Client Side Implementation
Java
// Java program to illustrate Client Side Programming
// for Simple Calculator using TCP
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Calc_Client
{
public static void main(String[] args) throws IOException
{
InetAddress ip = InetAddress.getLocalHost();
int port = 4444;
Scanner sc = new Scanner(System.in);
// Step 1: Open the socket connection.
Socket s = new Socket(ip, port);
// Step 2: Communication-get the input and output stream
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
while (true)
{
// Enter the equation in the form-
// "operand1 operation operand2"
System.out.print("Enter the equation in the form: ");
System.out.println("'operand operator operand'");
String inp = sc.nextLine();
if (inp.equals("bye"))
break;
// send the equation to server
dos.writeUTF(inp);
// wait till request is processed and sent back to client
String ans = dis.readUTF();
System.out.println("Answer=" + ans);
}
}
}
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
Server-Side Programming
Steps involved on the server 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 and returns the result back to client by writing on the outputStream of the socket.
- Close the connection.
Server Side Implementation
Java
// Java program to illustrate Server Side Programming
// for Simple Calculator using TCP
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
public class Calc_Server
{
public static void main(String args[]) throws IOException
{
// Step 1: Establish the socket connection.
ServerSocket ss = new ServerSocket(4444);
Socket s = ss.accept();
// Step 2: Processing the request.
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
while (true)
{
// wait for input
String input = dis.readUTF();
if(input.equals("bye"))
break;
System.out.println("Equation received:-" + input);
int result;
// Use StringTokenizer to break the equation into operand and
// operation
StringTokenizer st = new StringTokenizer(input);
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...");
// send the result back to the client.
dos.writeUTF(Integer.toString(result));
}
}
}
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.
Related Article:
Simple Calculator using UDP in Java
Similar Reads
Java Swing | Simple Calculator Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of Oracle's Java foundation classes . Java Swing is an API for providing graphical user interface elements to Java Programs.Swing was created to provide more powerful and flexible components than Java AWT (A
4 min read
Simple Calculator via UDP in Java 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
7 min read
Packet Capturing using JnetPcap in Java What is JnetPcap? JnetPcap is an open-source Java library. It is java wrapper for all libpcap library native calls. It can be used to capture both live as well as offline data. Decoding packets is a special feature of Jnetpcap. For processing packets, you need pcap files which can be generated by us
5 min read
How to Use Swing Applet in Java? In this article, we will be using the swing Applet or JApplet in Java. Here, we will make a simple multiplication application that will multiply the two input numbers. Approach to Using Swing Applet in JavaWe need to import the packages for Swing and AWT Components.Once the packages are imported, we
4 min read
Size of file on the Internet using Java To get the size of file from server first you need to connect to the server using URL and HttpURLConnection Class. To get the size of file we use getContentLength() method. As the size of file can be too large we use BigInteger class. You cannot use integer datatype as it can generate an error in ca
2 min read
Service Client Module in Java A Client Module in Java is a set of classes and methods that are used to connect to, interact with, and consume services from a server. It is the front-end component of a client/server architecture. It is typically responsible for initiating communication with the server, sending and receiving data,
6 min read
Connecting to an SFTP Server using Java JSch Library SFTP (Secure File Transfer Protocol) is a secure way to transfer files between a client and a server. It is similar to FTP (File Transfer Protocol) but is more secure as it uses SSH (Secure Shell) to encrypt the data being transferred. In this article, we will learn how to connect to an SFTP server
3 min read
URL getPort() method in Java with Examples The getPort() function is a part of URL class. The function getPort() returns the port of a specified URL. The function returns the port number or -1 if the port is not set Function Signature public int getPort() Syntax url.getPort() Return Type: The function returns Integer Type Parameter: This fun
2 min read
Java User Input - Scanner Class The most common way to take user input in Java is using the Scanner class. It is a part of java.util package. The scanner class can handle input from different places, like as we are typing at the console, reading from a file, or working with data streams. This class was introduced in Java 5. Before
4 min read
How to run Java RMI Application Prerequisite: RMI RMI (Remote Method Invocation) is used for distributed object references system. A distributed object is an object which publishes its interface on other machines. A Remote Object is a distributed object whose state is encapsulated. Stub and Skeleton are two objects used to communi
4 min read