import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
public class ShowBindings {
public static void main(String[] args) throws NamingException {
Context namingContext = new InitialContext();
NamingEnumeration<NameClassPair> e = namingContext.list("rmi:");
while (e.hasMore()) {
System.out.println(e.next().getName());
}
}
}
_______________________________________________________________________________________
RMIClient目录的文件:Product.java, ProductClient.java, client.policy, download/Product.class
// Product.java与服务器端的Product.java一样。
// ProductClient.java
import java.rmi.RMISecurityManager;
import javax.naming.Context;
import javax.naming.InitialContext;
public class ProductClient {
public static void main(String[] args) {
System.setProperty("java.security.policy", "client.policy");
System.setSecurityManager(new RMISecurityManager());
try {
String url = "rmi://localhost/";
Context namingContext = new InitialContext();
Product p1 = (Product) namingContext.lookup(url + "toaster");
Product p2 = (Product) namingContext.lookup(url + "microwave");
System.out.println(p1.getDescription());
System.out.println(p2.getDescription());
} catch (Exception e) {
e.printStackTrace();
}
}
}
// client.policy
grant {
permission java.net.SocketPermission
"*:1024-65535", "connect";
};
_______________________________________________________________________________________
运行步骤:
1. 启动RMI注册表
进入RMIServer目录,使用命令:rmiregistry &
(退出rmiregistry命令:killall rmiregistry,重新注册对象的时候要重启RMI注册表)
2.1 启动服务器:
进入RMIServer目录,使用命令:java ProductServer &
(退出服务器程序,ctr + c, 但还要使用再使用一次killall java, 否则再次启动服务器会报异常)
[2.2] 测试注册好的对象:
进入RMIServer目录,使用命令:java ShowBindings
3. 启动客户端:
java ProductClient
观察终端输出的结果。