Experiment 6
Experiment 6
AIM: To create a basic calculator using Java RMI (Remote Method Invocation). This
program includes the client and server, where the server performs the arithmetic operations
and the client interacts with the user.
The remote interface defines the methods that the client can invoke remotely.
import java.rmi.Remote;
import java.rmi. RemoteException;
1
G.Devans,23HQ1A4614
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
@Override
public double add(double a, double b) throws RemoteException {
return a + b;
}
@Override
public double subtract(double a, double b) throws RemoteException {
return a - b;
}
@Override
public double multiply(double a, double b) throws RemoteException {
return a * b;
}
@Override
public double divide(double a, double b) throws RemoteException {
2
G.Devans,23HQ1A4614
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return a / b;
}
}
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
public class CalculatorServer {
public static void main(String[] args) {
try {
// Start the RMI registry
LocateRegistry.createRegistry(1099);
import java.rmi.Naming;
import java.util.Scanner;
public class CalculatorClient {
public static void main(String[] args) {
try {
// Look up the CalculatorService from the RMI registry
Calculator calculator = (Calculator)
Naming.lookup("rmi://localhost/CalculatorService");
if (choice != 5) {
4
G.Devans,23HQ1A4614
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
switch (choice) {
case 1:
System.out.println("Result: " + calculator.add(num1, num2));
break;
case 2:
System.out.println("Result: " + calculator.subtract(num1, num2));
break;
case 3:
System.out.println("Result: " + calculator.multiply(num1, num2));
break;
case 4:
try {
System.out.println("Result: " + calculator.divide(num1, num2));
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
break;
default:
System.out.println("Invalid choice, please try again.");
}
}
5
G.Devans,23HQ1A4614
} while (choice != 5);
scanner.close();
System.out.println("Exiting the calculator...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
6
G.Devans,23HQ1A4614