详细步骤:
1:接口
package com.steven.remote;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Product extends Remote {
String getDescription() throws RemoteException;
}
2:实现类
package com.steven.remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class ProductImpl extends UnicastRemoteObject implements Product {
private String Desc;
public ProductImpl(String name)throws RemoteException {
// TODO Auto-generated constructor stub
Desc=name;
}
public String getDescription() throws RemoteException {
// TODO Auto-generated method stub
return "This is "+Desc+" product";
}
}
3:服务端
package com.steven.remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class ProductImpl extends UnicastRemoteObject implements Product {
private String Desc;
public ProductImpl(String name)throws RemoteException {
// TODO Auto-generated constructor stub
Desc=name;
}
public String getDescription() throws RemoteException {
// TODO Auto-generated method stub
return "This is "+Desc+" product";
}
}
4:客户端
package com.steven.remote;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
public class ProductClient {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("begin to invoke remote method");
//System.setSecurityManager(new RMISecurityManager());
String url = "rmi://192.168.5.155:1099/";
try {
System.out.println("1");
Product c1 = (Product) Naming.lookup(url + "toaster");
Product c2 = (Product) Naming.lookup(url + "microwave");
System.out.println("2");
System.out.println(c1.getDescription());
System.out.println("3");
System.out.println(c2.getDescription());
} catch (Exception ex) {
System.out.println("error " + ex);
}
}
}
5:注意事项
1:请注意客户端代码如果添加安全认证,则远程调用会出现访问拒绝异常.
2:客户端需要: Product.class ,ProductClient .class,ProductImpl_Stub.class(接口,客户端类,存根)
3:存根的生成:a:先编译所有类生成.class文件.b:在dos窗口下使用 rmic ProductImpl(实现类)
4:实现类必须继承UnicastRemoteObject