Code for RMI program of count server and client in Java
// CountRMIImpl.java, CountRMI implementation
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
publicclass CountRMIImpl extends UnicastRemoteObject
implements CountRMI
{
privateint sum;
public CountRMIImpl(String name) throws RemoteException
{
super();
try
{
Naming.rebind(name, this);
sum = 0;
} catch (Exception e)
{ System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
}
}
publicint sum() throws RemoteException
{ return sum;
}
publicvoid sum(int val) throws RemoteException
{ sum = val;
}
publicint increment() throws RemoteException
{ sum++;
return sum;
}
}
// CountRMIClient.java RMI Count client
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
publicclass CountRMIClient
{ publicstaticvoid main(String args[])
{ // Create and install the security manager
System.setSecurityManager(new RMISecurityManager());
try
{
//CountRMI myCount = (CountRMI)Naming.lookup("rmi://"// + args[0] + "/" + "myCountRMI");
CountRMI myCount = (CountRMI)Naming.lookup("//"
+ args[0] + "/" + "myCountRMI");
// Set Sum to initial value of 0
System.out.println("Setting Sum to 0");
myCount.sum(0);
// Calculate Start timelong startTime = System.currentTimeMillis();
// Increment 1000 times
System.out.println("Incrementing");
for (int i = 0 ; i < 1000 ; i++ )
{ myCount.increment();
}
// Calculate stop time; print out statisticslong stopTime = System.currentTimeMillis();
System.out.println("Avg Ping = "
+ ((stopTime - startTime)/1000f)
+ " msecs");
System.out.println("Sum = " + myCount.sum());
} catch(Exception e)
{ System.err.println("System Exception" + e);
}
System.exit(0);
}
}
// CountRMIServer.java
import java.rmi.*;
import java.rmi.server.*;
publicclass CountRMIServer
{
publicstaticvoid main(String args[])
{
// Create and install the security manager
System.setSecurityManager(new RMISecurityManager());
try
{
// Create CountRMIImpl
CountRMIImpl myCount = new CountRMIImpl("//xyz/myCountRMI");
System.out.println("CountRMI Server ready.");
} catch (Exception e)
{ System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
}
}
}