Search code examples
javarefactoringrmi

Accessing objects using RMI


Class FoodItem{ 
 private String name; 
 private int numCalories; 

 public FoodItem(String s, int cals) 
 { 
 name = s; 
 numCalories = cals 
 } 
 public String getName() 
 { 
 return name; 
 } 
 public int getNumOfCalories() 
 { 
 return numCalories; 
 } 
}

public class FoodItemServer 
{ 
 public static void main(String [] args) 
 { 
 FoodItem f1 = new FoodItem("Wispa", 254); 
 FoodItem f2 = new FoodItem("Apple", 45); 
 System.out.println( "Food Name: " + f1.getName + “has “ +
 f1.getCalories +“calories”); 
 } 
} 

We've recently started using RMI and i'm struggling to understand it.

In a previous example, (I'll put it below) we used a factory to store our objects and used Naming.rebind() in the server class on the instance we called from our factory.

In the example above, i only have the Implementation and server classes, a factory is not being used, how could i re-factor the code so that i could access the objects remotely, would i use the Naming.rebind() again or is there another implementation?

This is what i used before:

import java.rmi.Naming;

/*
 * Creates the server for using RMI
 */
public class PlayerServer 
{
    public static void main(String args[])
    {
          System.out.println("Player Server Starting");
            try{
                PlayerFactory aFactory = PlayerFactory.getInstance();
                Naming.rebind("factory", aFactory);
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }

Solution

  • In Order to use RMI you need an Interface which implement java.rmi.Remote interface and your FoodItemServer must extends from java.rmi.server.UnicastRemoteObject and implement this interface.

    Additionally you need to register this class at a RMIRegistry which has to be started additionally. This is a special server which provides an JNDI Interface.

    A client can than ask the RMIRegistry in order to receive an instance of the type of the RMI Remote Interface using the java.naming mechanism,