Lab Assignment 3
Develop a ’Client Server’ based application using ’Java RMI’ to perform remote Arithmetic
Operations such as addition, substraction, multiplication and division. The input/values to the above
stated operations will be provided from the client side, by the users.
SOLUTION->
1)Remote Interface (CalcIntf.java)):
import java.rmi.*;
public interface CalcIntf extends Remote {
int add(int a, int b) throws RemoteException;
int subtract(int a, int b) throws RemoteException;
int multiply(int a, int b) throws RemoteException;
int divide(int a, int b) throws RemoteException;
}
2)Server Implementation (CalculatorServer.java):
import java.rmi.*;
import java.rmi.server.*;
public class CalculatorServer extends UnicastRemoteObject implements CalcIntf {
public CalculatorServer() throws RemoteException {
super();
}
@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}
@Override
public int subtract(int a, int b) throws RemoteException {
return a - b;
}
@Override
public int multiply(int a, int b) throws RemoteException {
return a * b;
}
@Override
public int divide(int a, int b) throws RemoteException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
public static void main(String[] args) {
try {
CalculatorServer server = new CalculatorServer();
Naming.rebind("rmi://localhost/Calculator", server);
System.out.println("Calculator Server is ready.");
} catch (Exception e) {
System.out.println("Server exception: " + e);
}
}
}
3)Client Implementation (ClientCalc.java):
import java.rmi.*;
import java.rmi.registry.*;
import java.util.Scanner;
public class ClientCalc {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
CalcIntf calculator = (CalcIntf) Naming.lookup("rmi://localhost/Calculator");
Scanner obj = new Scanner(System.in);
System.out.println("Enter first value: ");
int a = obj.nextInt();
System.out.println("Enter second value: ");
int b = obj.nextInt();
System.out.println("Enter operation (+, -, *, /): ");
char operation = obj.next().charAt(0);
int result = 0;
switch (operation) {
case ’+’:
result = calculator.add(a, b);
break;
case ’-’:
result = calculator.subtract(a, b);
break;
case ’*’:
result = calculator.multiply(a, b);
break;
case ’/’:
if (b != 0) {
result = calculator.divide(a, b);
} else {
System.out.println("Error: Division by zero.");
return;
}
break;
default:
System.out.println("Invalid operation.");
return;
}
System.out.println("Result: " + result);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}