0% found this document useful (0 votes)
4 views4 pages

Distributed Calculator Source Code

This document outlines a distributed calculator application implemented using Java Sockets, featuring a multi-threaded server that can handle multiple clients. It includes source code for the server, client handler, and client, along with instructions for compiling and running the application. The client communicates with the server using a simple protocol to perform arithmetic operations based on user input.

Uploaded by

rasdavitiman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views4 pages

Distributed Calculator Source Code

This document outlines a distributed calculator application implemented using Java Sockets, featuring a multi-threaded server that can handle multiple clients. It includes source code for the server, client handler, and client, along with instructions for compiling and running the application. The client communicates with the server using a simple protocol to perform arithmetic operations based on user input.

Uploaded by

rasdavitiman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Distributed Calculator using Java Sockets

Client-Server Implementation

November 16, 2025

1 Introduction
This document provides the complete source code for a distributed calculator application using
Java Sockets. The server is multi-threaded to handle multiple clients concurrently, and the client
communicates a simple protocol: OPERATOR NUM1 NUM2 (e.g., + 10 5).

2 Calculator Server ([Link])


The main server class listens for incoming client connections and delegates each connection to
a new ClientHandler thread.
1 import [Link]. ServerSocket ;
2 import [Link]. Socket ;
3 import [Link]. IOException ;
4
5 public class CalculatorServer {
6 private static final int PORT = 12345;
7
8 public static void main( String [] args) {
9 try ( ServerSocket serverSocket = new ServerSocket (PORT)) {
10 System .out. println ("� Calculator Server running on port " + PORT + ". Waiting
for connections ...");
11
12 // Server runs forever , accepting clients
13 while (true) {
14 Socket clientSocket = serverSocket . accept ();
15 System .out. println ("\�n Client connected from: " + clientSocket .
getInetAddress (). getHostAddress ());
16
17 // Start a new thread to handle the client 's request
18 new ClientHandler ( clientSocket ). start ();
19 }
20 } catch ( IOException e) {
21 System .err. println (" Server exception : " + e. getMessage ());
22 }
23 }
24 }

Listing 1: [Link]

3 Client Handler Thread ([Link])


This class handles the core logic of reading the expression, performing the calculation, and
writing the result back to the client.

1
1 import [Link]. Socket ;
2 import [Link]. BufferedReader ;
3 import [Link]. InputStreamReader ;
4 import [Link]. PrintWriter ;
5 import [Link]. IOException ;
6
7 public class ClientHandler extends Thread {
8 private final Socket clientSocket ;
9
10 public ClientHandler ( Socket socket ) {
11 this. clientSocket = socket ;
12 }
13
14 @Override
15 public void run () {
16 try ( BufferedReader reader = new BufferedReader (new InputStreamReader (
clientSocket . getInputStream ()));
17 PrintWriter writer = new PrintWriter ( clientSocket . getOutputStream (), true))
{
18
19 String inputLine ;
20 // Read lines until the client disconnects or sends an empty line
21 while (( inputLine = reader . readLine ()) != null) {
22 System .out. println (" -> Received request : " + inputLine );
23 String result = calculate ( inputLine );
24 writer . println ( result );
25 System .out. println (" -> Sent result : " + result );
26 }
27
28 } catch ( IOException e) {
29 System .out. println (" Client disconnected or I/O error : " + e. getMessage ());
30 } finally {
31 try {
32 clientSocket . close ();
33 } catch ( IOException e) {
34 System .err. println (" Error closing socket : " + e. getMessage ());
35 }
36 }
37 }
38
39 /**
40 * Parses the input string " OPERATOR NUM1 NUM2" and performs the calculation .
41 */
42 private String calculate ( String expression ) {
43 String [] parts = expression . split (" ");
44 if ( parts . length != 3) {
45 return " ERROR : Invalid format . Use: OPERATOR NUM1 NUM2";
46 }
47
48 String operator = parts [0];
49 try {
50 double num1 = Double . parseDouble ( parts [1]);
51 double num2 = Double . parseDouble ( parts [2]);
52 double result = 0;
53
54 switch ( operator ) {
55 case "+":
56 result = num1 + num2;
57 break ;
58 case "-":
59 result = num1 - num2;
60 break ;
61 case "*":

2
62 result = num1 * num2;
63 break ;
64 case "/":
65 if (num2 == 0) {
66 return " ERROR : Division by zero is not allowed .";
67 }
68 result = num1 / num2;
69 break ;
70 default :
71 return " ERROR : Unsupported operator : " + operator ;
72 }
73 // Format result to a string
74 return String . valueOf ( result );
75
76 } catch ( NumberFormatException e) {
77 return " ERROR : Invalid numbers provided .";
78 }
79 }
80 }

Listing 2: [Link]

4 Calculator Client ([Link])


The client connects to the server and handles user input via the console, sending the expression
and displaying the returned result.
1 import [Link]. Socket ;
2 import [Link]. BufferedReader ;
3 import [Link]. InputStreamReader ;
4 import [Link]. PrintWriter ;
5 import [Link]. Scanner ;
6 import [Link]. IOException ;
7
8 public class CalculatorClient {
9 private static final String SERVER_ADDRESS = " localhost ";
10 private static final int SERVER_PORT = 12345;
11
12 public static void main( String [] args) {
13 System .out. println (" Connecting to Calculator Server at " + SERVER_ADDRESS + ":" +
SERVER_PORT );
14
15 try ( Socket socket = new Socket ( SERVER_ADDRESS , SERVER_PORT );
16 BufferedReader reader = new BufferedReader (new InputStreamReader ( socket .
getInputStream ()));
17 PrintWriter writer = new PrintWriter ( socket . getOutputStream (), true);
18 Scanner scanner = new Scanner ( System .in)) {
19
20 System .out. println ("� Connection successful .");
21 System .out. println (" Enter expression (e.g., + 10 5). Type 'exit ' to quit.");
22
23 String userInput ;
24 while (true) {
25 System .out. print ("Client > ");
26 userInput = scanner . nextLine ();
27
28 if ("exit". equalsIgnoreCase ( userInput .trim ())) {
29 System .out. println (" Client shutting down ...");
30 break ;
31 }
32

3
33 // Send the expression to the server
34 writer . println ( userInput );
35
36 // Read and display the server 's response
37 String response = reader . readLine ();
38 if ( response != null) {
39 System .out. println (" Server Response : " + response );
40 } else {
41 // Server closed the connection
42 System .out. println (" Server disconnected .");
43 break ;
44 }
45 }
46
47 } catch ( IOException e) {
48 System .err. println (" Client error : Could not connect or I/O failure : " + e.
getMessage ());
49 }
50 }
51 }

Listing 3: [Link]

5 Instructions to Run the Application


1. Save Files: Save the code above into three separate files: [Link], [Link]
and [Link].

2. Compile: Open a terminal and compile all files: $$javac [Link] [Link]
[Link]

3. Start Server (Terminal 1): Run the server in the first terminal window. It will wait for
connections: $$java CalculatorServer

4. Start Client (Terminal 2): Open a second terminal and run the client: $$java CalculatorClient

5. Interact: In the client terminal, enter expressions like * 4 5 or / 22 7 and observe the
server processing the request.

You might also like