Implementation of Remote InterfaceFigure 4.1
Listing 4.2 GreaterServerImpl.java (Complete code)import java.rmi.*; import java.rmi.server.*; //server class public class GreaterServerImpl implements GreaterInterface{ //constructor public GreaterServerImpl() throws RemoteException{ System.out.println("Creating server object"); } //remote method called by clients public String getGreater(int one,int two) throws RemoteException{ if(one > two) return one +" is greater"; else if(two > one) return two +" is greater" ; else return "Equal" ; } //main method public static void main(String args[]) throws Exception{ //server instance GreaterServerImpl obj = new GreaterServerImpl(); //explicitly exporting remote object UnicastRemoteObject.exportObject(obj); //bind with the registry service Naming.rebind("Server",obj); } } Explanation of CodeImport necessary packages. import java.rmi.*; import java.rmi.server.*; The implementation class declares which remote interface(s) it is implementing. Here is the GreaterServerImpl class declaration: public class GreaterServerImpl implements GreaterInterface{
//constructor public GreaterServerImpl() throws RemoteException{ System.out.println("Creating server object"); } Here is the implementation for the getGreater() method, which compares two given numbers and returns the greater number. //remote method called by clients public String getGreater(int one,int two) throws RemoteException{ if(one > two) return one +" is greater"; else if(two > one) return two +" is greater" ; else return "Equal" ; }
The main method of the server creates one or more instances of the remote object implementation, which provides the service. For example: GreaterServerImpl obj = new GreaterServerImpl(); The following line explicitly exports the remote object to make it available to receive incoming calls, using an anonymous port. //explicitly exporting remote
object Rebinding the specified name to a remote object. //bind with the regsitry service |
||||
|
||||
Copyright © 2001 www.universalteacher.com |
||||