Java RMI Calculator Implementation

Classified in Computers

Written on in English with a size of 2.75 KB

1. CalculatorInterface.java

The following code defines the Remote Interface for the calculator application.

import java.rmi.*;

public interface CalculatorInterface extends Remote {
    public int add(int num1, int num2) throws RemoteException;
    public int subtract(int num1, int num2) throws RemoteException;
    public int multiply(int num1, int num2) throws RemoteException;
    public int divide(int num1, int num2) throws RemoteException;
}

2. ServerCalculator.java

This class implements the CalculatorInterface and extends UnicastRemoteObject to handle remote calls.

import java.rmi.*;
import java.rmi.server.*;

public class ServerCalculator extends UnicastRemoteObject implements CalculatorInterface {
    public ServerCalculator() throws RemoteException {
        super();
    }

    public int add(int num1, int num2) throws RemoteException {
        int temp;
        temp = num1 + num2;
        return temp;
    }

    public int subtract(int num1, int num2) throws RemoteException {
        int temp;
        temp = num1 - num2;
        return temp;
    }

    public int multiply(int num1, int num2) throws RemoteException {
        int temp;
        temp = num1 * num2;
        return temp;
    }

    public int divide(int num1, int num2) throws RemoteException {
        int temp;
        temp = num1 / num2;
        return temp;
    }
}

3. RegisterIt.java

The RegisterIt class is responsible for instantiating the server and binding it to the RMI registry.

import java.rmi.*;

public class RegisterIt {
    public static void main(String[] args) {
        try {
            ServerCalculator cal = new ServerCalculator();
            System.out.println("Object is instantiated: " + cal);
            Naming.rebind("/ServerCalculator", cal);
            System.out.println("Hello Server bound in registry");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

4. ClientCalculator.java

The client-side application looks up the remote object and performs arithmetic operations.

import java.rmi.*;

public class ClientCalculator {
    public static void main(String[] args) {
        try {
            CalculatorInterface cal = (CalculatorInterface) Naming.lookup("/ServerCalculator");
            System.out.println("Addition of 3, 2 is " + cal.add(3, 2));
            System.out.println("Subtraction of 3, 2 is " + cal.subtract(3, 2));
            System.out.println("Addition of 2, 3 is " + cal.add(2, 3));
            System.out.println("Addition of 6, 2 is " + cal.add(6, 2));
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Related entries: