20-CS-694 Advanced Programming Techniques Spring 2012
Networking

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

     Previous      Next     Times.java     TimesServer.java     TimesImpl.java      All lectures

Remote Method Invocation

Remote Method Invocation. This and the next two slides show a second example that implements the next method of a class that multiplies all (presumably integer) tokens of a stream by a given amount. A set method is used to fix the amount to multiply. In previous examples a Times class was developed and the constructor was used to set the multiplier.

Times.java

// Establish the interface Times.java
import java.rmi.Remote; 
import java.rmi.RemoteException; 

public interface Times extends Remote {
   public void putIt (Object t) throws RemoteException;
	
   public Object next () throws RemoteException;
	
   public void set (int n, Stream s) throws RemoteException;	
}
TimesServer.java
// Register the class TimesServer.java
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;

public class TimesServer {
   public static void main(String args[]) {
      if (System.getSecurityManager() == null)
         System.setSecurityManager(new RMISecurityManager()); 

      try { 
         TimesImpl obj = new TimesImpl(); 
         Naming.rebind("Times", obj); 
         System.out.println("Times bound in registry"); 
      }
      catch (Exception e) { 
         System.out.println("TimesServer err: " + e.getMessage()); 
         e.printStackTrace(); 
      }
   }
}
TimesImpl.java
// Implementation details TimesImpl.java
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;

public class TimesImpl extends StreamImpl implements Times {
   IntObject token;
   int number;
   Stream stream;

   public TimesImpl () throws RemoteException { }
   
   public void set (int n, Stream s) throws RemoteException {
      stream = s;
      number = n;
   }
   
   public void run () {
      while (true) {
         try {
            token = new IntObject(number*((IntObject)stream.next()).valueOf());
            putIt(token);
         }
         catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
         }
      }
   }
}