我有一个试图互相通信的客户端和服务器程序.在服务器的策略文件中,我指定了以下内容:
grant signedBy "vivin" {
permission java.io.FilePermission "-", "read, write";
permission java.net.SocketPermission "localhost:2220-2230", "accept, connect, listen, resolve", signedBy "vivin";
};
在客户的策略文件中,我有:
grant signedBy "vivin" {
permission java.net.SocketPermission "localhost:2220-2230", "accept, connect, listen, resolve", signedBy "vivin";
};
我启动服务器,它侦听端口2225.然后启动客户端,它尝试连接到正在侦听端口2225的服务器.不幸的是,我在服务器上收到此错误:
[java] Exception in thread "main" java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:45944 accept,resolve)
[java] at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
[java] at java.security.AccessController.checkPermission(AccessController.java:546)
[java] at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
[java] at java.lang.SecurityManager.checkAccept(SecurityManager.java:1157)
[java] at java.net.ServerSocket.implAccept(ServerSocket.java:457)
[java] at java.net.ServerSocket.accept(ServerSocket.java:421)
端口号不断变化;我假设这是客户端的端口号(服务器连接到客户端的端口号?).那是对的吗?对于此分配,在端口号上指定了限制:
Your client and server should use the Java Security manager, and your project must include policy files for each that defines the necessary permissions for them to run. Allow your server and client to contact each other on localhost using ports in the range 2220-2230.
我如何遵守此限制?还是仅适用于服务器侦听的端口?我认为,如果我为大于2231的端口提供接受和解析权限,则可以使其正常工作.但是我不知道这是否违反了限制.
解决方法:
因为客户端随机选择了它的本地tcp端口(我想),所以您应该给予它适当的权限:
grant signedBy "vivin" {
permission java.net.SocketPermission "localhost:1024-", "connect, resolve", signedBy "vivin";
};
客户端不在侦听传入的连接,并且不需要“监听”和“接受”的权限.在服务器上,只要服务器未建立传出的TCP连接,就可以放弃“连接”的权限.