1. The simplest example of RMI, the idea is that you create a method addData () in the server side, this method implements the addition of two integers, but you add this method from the client remote call.
2. Let's take a step by step, first define the remote interface ----- Remote Interface class
Import java.rmi. *;
Import java.rmi.server. *;
Public Interface Addserver Extends Remote
{
Public Int Adddata (int A, int b).
}
2. Define and implement remote methods in servers ----- Server class
Import java.rmi. *;
Import java.rmi.server. *;
/ / Note To expand the UnicastremoteObject class
Public Class AddserverImpl Extends UnicastRemoteObject IMPLEments Addserver
{
Public AddserverImpl () THROWS RemoteException
{
Super ();
}
Public Int Adddata (int A, int b) throws remoteException
{
RETURN A B;
}
Public static void main (string s [])
{
Try
{
// Create this remote object
AddserverImpl instance = new addserverImpl ();
/ / Register this remote object
Naming.Rebind ("add", instance);
System.out.Println ("Server Registered");
}
Catch (Exception E) {system.out.println (e);
}
}
3. Define and implement customers ----- Customer class
Import java.io. *;
Import java.rmi. *;
Public Class AddClient
{
Public AddClient ()
{
Try
{
BufferedReader Input = New BufferedReader (NEW InputStreamReader (System.in);
System.out.println ("please enter first number:");
System.out.flush ();
String s = INPUT.READLINE ();
INT Num1 = Integer.Parseint (s);
System.out.println ("please enter second number:");
System.out.flush ();
S = INPUT.READLINE ();
INT Num2 = Integer.Parseint (s);
Addserver Addserver = (addserver) Naming.lookup ("RMI: //127.0.0.1/add");
INT i = addserver.adddata (Num1, Num2);
System.out.print ("Result IS:" i);
}
Catch (Exception E) {system.out.println (e);
}
Public static void main (string s [])
{
New addclient ();
}
}
4. Compile javac * .java
5. Generate Stub and Skeleton
At the command prompt: RMIC AddserveerImpl
At this point you will find more files in the folder, addServerImpl_skel.class and addserverimpl_stub.class6. Create a security policy
At the command prompt: PolicyTool
Click the Add Policy Entry button
Click the Add Permission button
Pick up in the Permission list box: Allpermission
Click OK
Click Done button
From the File menu, select Save As, enter the file name .java.policy, then save the folder of your login user name below
7. Start the RMI remote registry
At the command prompt: Start RMIREGISTRY
8. Start the server
At the command prompt: Java AddserveerImpl
9. Start customers
At the command prompt: Java AddClient
10. If you are debugging on your own machine, you can go to the ninth step. If you debug on the two machines, you need to change the IP address in the AddClient code, and put addclient.class, addserver.class And addServerImpl_stub.class placed on the machine you intend to be used as the client, pay attention to other files don't put, otherwise you will wait to tell others about the server code.