在 RMI 服务器的 RMI 主机中使用“0.0.0.0”代替“localhost”。
EDIT1
以下是另一组更改:
- 在您希望服务器监听的端口上创建一个注册表
LocateRegistry.createRegistry(port)
- 您的 RMI 类
Addition 应该是可序列化的(通过 UnicastRemoteObject 实现)
- RMI 方法应在其签名中添加
RemoteException。
- RMI 客户端应该知道远程机器的名称/端口(在本例中为
box01 / 1091)。
另外请注意,您选择的端口不应已被任何其他服务占用。比如端口1099。
下面是有效的代码:
AdditionalInterface.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface AdditionalInterface extends Remote {
public int Add(int a, int b) throws RemoteException;
}
Addition.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Addition extends UnicastRemoteObject implements
AdditionalInterface {
private static final long serialVersionUID = 1L;
public Addition() throws RemoteException {
// TODO Auto-generated constructor stub
}
public int Add(int a, int b) {
return a + b;
}
}
AdditionServer.java
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
public class AdditionServer {
public static void main(String[] argv) throws RemoteException {
Addition Hello = new Addition();
int port = 1091;
try { // special exception handler for registry creation
LocateRegistry.createRegistry(port);
System.out.println("java RMI registry created.");
} catch (RemoteException e) {
// do nothing, error means registry already exists
System.out.println("java RMI registry already exists.");
}
String hostname = "0.0.0.0";
String bindLocation = "//" + hostname + ":" + port + "/Hello";
try {
Naming.bind(bindLocation, Hello);
System.out.println("Addition Server is ready at:" + bindLocation);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
System.out.println("Addition Serverfailed: " + e);
}
}
}
AdditionClient
import java.net.MalformedURLException;
import java.rmi.*;
public class AdditionClient {
public static void main(String[] args) {
String remoteHostName = "box01";
int remotePort = 1091;
String connectLocation = "//" + remoteHostName + ":" + remotePort
+ "/Hello";
AdditionalInterface hello = null;
try {
System.out.println("Connecting to client at : " + connectLocation);
hello = (AdditionalInterface) Naming.lookup(connectLocation);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NotBoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int result = 0;
try {
result = hello.Add(9, 10);
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Result is :" + result);
}
}