我正在为我在 Netbeans 中的类作业创建 RMI 程序。这是一个简单的 RMI 程序,服务器端工作正常。但是当我运行我的客户端文件时。它最终给我错误
Exception in thread "main" java.security.AccessControlException: access denied ("java.net.SocketPermission" "127.0.0.1:1099" "connect,resolve")
此外,它在客户端代码的第 26 行说了一些错误。 为了清楚地理解,我给出了所有三个文件的完整代码。
接口(interface).java :
package RMI;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface DemoInterface extends Remote {
public String SayDemo() throws RemoteException;
}
服务器.java
package RMI;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Interface{
public Server()
{
super();
}
private String message;
public Server(String msg) throws RemoteException
{
message = msg;
}
public static void main(String[] args) {
try {
DemoInterface h = new Server("Hello");
DemoInterface stub = (DemoInterface) UnicastRemoteObject.exportObject(h,0);
LocateRegistry.createRegistry(4096);
Registry registry = LocateRegistry.getRegistry("127.0.0.1",4096);
registry.rebind("Hello", stub);
System.out.println("Server is connected and ready to use");
}
catch(Exception e)
{
System.out.println("server not connected\n"+e);
}
}
@Override
public String SayDemo() throws RemoteException {
System.out.println("Server.saydemo override");
return message;
}
}
客户端.java
package RMI;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) {
if(System.getSecurityManager() == null)
{
System.setSecurityManager(new SecurityManager());
}
try {
Registry reg = LocateRegistry.getRegistry("127.0.0.1", 4096);
System.out.println("in try after reg locate");
DemoInterface h = (DemoInterface) reg.lookup("Hello");//Error Showed on this line by netbeans
System.out.println(h.SayDemo());
}
catch(RemoteException | NotBoundException e)
{
System.out.println(""+e );
}
}
}
请指导我哪里错了。提前谢谢你。
最佳答案
您在客户端main
方法中设置了一个SecurityManager
。您是否还提供了安全策略文件?默认策略不是很宽松,并且拒绝 Socket 操作等。
您可以像这样指定允许所有代码库的所有权限的策略。
grant {
permission java.security.AllPermission;
};
将它添加到您的命令行以调用 java
。将 mypolicy
替换为您的策略文件,并将 SomeApp
替换为您的主类。 注意第二个参数中的两个 =
字符
java -Djava.security.manager -Djava.security.policy==mypolicy SomeApp
请注意,这不是在生产环境中运行 RMI 的安全策略(RMI 可以加载远程代码库)。
正确使用 SecurityManager
类和策略配置是一个复杂的主题,为了进一步阅读,我建议 Java SE 7 Security Documentation特别是 Default Policy Implementation and Policy File Syntax
关于java - RMI 程序 : Client side giving Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19323762/