
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 Using TCP in Java
The Internet Protocol suite contains all sort of protocols that enables communication between devices over the Internet. TCP is the most common protocol of this suite. It is a connection-oriented protocol, which means it maintains the established connection between two devices till the end of a communication. This is the reason it is used while web surfing, sending emails and transferring files.
In this article, we will develop a simple client-server side calculator using TCP in Java. The client will request the operation and the server will send the result to client device after calculating it.
Java Networking
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.
Socket
It is the base of Java networking concept, it allows a device to serve various clients at once. There are two kinds of TCP socket classes. One is ?ServerSocket' class used for servers that receive and sends result to client device and the other one is ?Socket' class used on client side to request information.
I/O Streams
Stream is an abstraction that is used while performing Input and Output operations in Java networking. By using the ?getInputStream()' and ?getOutputStream()', we can access the input and output streams associated with ?Socket' class.
Program of Calculator using TCP
Program of Client Side
Working of code
We first import the two most important packages named ?java.net' to access all the classes regarding Java networking and ?java.io' for input and output streams. The ?java.util' package to use ?Scanner' class.
Fetch the LocalHost address and then, store the port number and address in the object of ?Socket' class.
Define two objects named ?inpStrm' to receive data and ?outpStrm' to send the data in the form of streams.
Now, inside the try block, we will ask for user input to request an operation and to receive the result accordingly.
Example
import java.io.*; import java.net.*; import java.util.*; public class ClientCal { public static void main(String[] args) throws IOException { // fetching address of localhost InetAddress addr = InetAddress.getLocalHost(); Scanner inp = new Scanner(System.in); // establishing socket connection Socket sock = new Socket(addr, 6666); // to send and receive data through streams DataInputStream inpStrm = new DataInputStream(sock.getInputStream()); DataOutputStream outpStrm = new DataOutputStream(sock.getOutputStream()); 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: "); int oprtr = inp.nextInt(); // Type 0 for cut the connection if (oprtr == 0) { break; } // sending the operator for operation outpStrm.writeInt(oprtr); // reading result from server String res = inpStrm.readUTF(); System.out.println("Your Result for the given operation = " + res); } } // to handle exception catch(Exception exp) { System.out.println(exp); } } }
Program of Server Side
Working of code
First, establish a connection with the client.
Then read the request from client side.
Inside the try block, using switch case we perform the operation and send the result to client device.
Catch block is used to handle any kind of exception during run time.
Example
import java.io.*; import java.net.*; import java.util.*; public class ServeCalc { public static void main(String args[]) throws IOException { // establishing the socket connection ServerSocket Serve = new ServerSocket(6666); Socket sock = Serve.accept(); // to send and receive data through streams DataInputStream inpStrm = new DataInputStream(sock.getInputStream()); DataOutputStream outpStrm = new DataOutputStream(sock.getOutputStream()); try { while (true) { // reading input from client int oprtr = inpStrm.readInt(); System.out.println("Client has requested for " + oprtr + " operation"); int res = 0; int data1 = 15; int data2 = 5; switch(oprtr) { case 1 : res = data1 + data2; outpStrm.writeUTF(Integer.toString(res)); break; case 2 : res = data1 - data2; outpStrm.writeUTF(Integer.toString(res)); break; case 3 : res = data1 * data2; outpStrm.writeUTF(Integer.toString(res)); break; case 4 : res = data1 / data2; outpStrm.writeUTF(Integer.toString(res)); break; default : outpStrm.writeUTF(" You have given invalid choice! "); break; } System.out.println("Result sent to the client..."); } } // to handle exception catch(Exception exp) { System.out.println(exp); } } }
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 Server side
D:\Java Programs>javac ServeCalc.java D:\Java Programs>java ServeCalc Client has requested for 1 operation Result sent to the client... Client has requested for 2 operation Result sent to the client... Client has requested for 3 operation Result sent to the client... Client has requested for 4 operation Result sent to the client... java.net.SocketException: Connection reset
Output on Client side
D:\Java Programs>javac ClientCal.java D:\Java Programs>java ClientCal 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 Type 1 for Addition Type 2 for Subtraction Type 3 for Multiplication Type 4 for Division Enter your choice: 2 Your Result for the given operation = 10 Enter your choice: 0
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, discussed server-side and client-side programs of a simple calculator using Transmission Control Protocol. We discovered how we could establish a connection between client and server devices in Java.