我尝试了一个简单的 java rmi 程序,其中客户端对服务器进行远程调用,服务器返回一个字符串。它与通过局域网连接的两台计算机完美配合。如何实现客户端的远程调用,该客户端未通过局域网连接到服务器但服务器和客户端都连接到互联网?我通过将 Client.java 中的 'localhost' 更改为服务器的 IP 地址来尝试以下简单代码。没用。我需要什么才能进行这样的远程调用?
//远程接口 -> MyInterface.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface MyInterface extends Remote
{
public String SaySomething() throws RemoteException;
}
//客户端.java
import java.rmi.*;
import java.rmi.registry.*;
public class Client
{
public static void main(String []args)
{
System.setProperty( "java.security.policy", "client.policy" );
if (System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
try {
String name = "MyInterface";
Registry registry = LocateRegistry.getRegistry("localhost",4501);
MyInterface mi = (MyInterface) registry.lookup(name);
System.out.println(mi.SaySomething());
} catch (Exception e) {
e.printStackTrace();
}
}
}
//服务器.java
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.UnicastRemoteObject;
public class Server implements MyInterface
{
public Server()
{
super();
}
public String SaySomething()
{
return "Server Speaking";
}
public static void main(String []args)
{
System.setProperty( "java.security.policy", "server.policy" );
if(System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
try {
String name = "MyInterface";
MyInterface mi = new Server();
MyInterface stub =(MyInterface) UnicastRemoteObject.exportObject(mi,4501);
Registry registry = LocateRegistry.createRegistry(4501);
registry.rebind(name, stub);
System.out.println("Server bound");
} catch (Exception e) {
System.out.println("oops");
}
}
}
我得到以下异常: java.security.AccessControlException:在 java.security.AccessController.checkPermission 的 java.security.AccessControlContext.checkPermission(AccessControlContext.java:366) 的访问被拒绝 ("java.net.SocketPermission" "xxxx:4501" "connect,resolve") (AccessController.java:555) 在 java.lang.SecurityManager.checkPermission(SecurityManager.java:549) 在 java.lang.SecurityManager.checkConnect(SecurityManager.java:1051) 在 java.net.Socket.connect(Socket.java: 574) 在 java.net.Socket.connect(Socket.java:528) 在 java.net.Socket.(Socket.java:425) 在 java.net.Socket.(Socket.java:208) 在 sun.rmi。位于 sun.rmi.transport.proxy.RMIMasterSocketFactory 的 transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)。createSocket(RMIMasterSocketFactory.java:146) 在 sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613) 在 sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216) 在 sun.rmi .transport.tcp.TCPChannel.newConnection(TCPChannel.java:202) 在 sun.rmi.server.UnicastRef.newCall(UnicastRef.java:340) 在 sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source) 在 Client.main (Client.java:14)爪哇:14)爪哇:14)