Tuesday, August 31, 2010

Remote method Invocation (RMI)

Remote method invocation is used to invoke methods across the networks...... The objects have to be registered in the rmi-registry..... Its like the yellow pages where all the entries are registered. From the Rmi- Registry we can access the objects but the service name has to be known to access the objects.


Remote Interface :


import java.rmi.Remote;
import java.rmi.RemoteException;

public interface remote extends Remote {
    int getSum(int a,int b) throws RemoteException;
}

Server :




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

public class server extends UnicastRemoteObject
                           implements remote
{
    public server() throws RemoteException {
        super();
    }

    public int getSum(int a,int b) {
return a+b;
    }

    public static void main(String[] args) {
      
        try {
            server engine = new server();
            Naming.rebind("samplermi", engine);
            System.out.println("Server bound");
        } catch (Exception e) {
            System.err.println("server exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Naming.rebind() method puts the engine object in the name "samplermi".

Client :

// Java Document

import java.rmi.*;

public class client {
    public static void main(String args[]) {
try {
            remote obj = (remote) Naming.lookup("samplermi");
            System.out.println(obj.getSum(10,20));
        } catch (Exception e) {
            System.err.println("client exception: " + e.getMessage());
            e.printStackTrace();
        }
    }  
}

The client access the remote object using the "samplermi" service name.