这是我第一次使用 RMI,基本上我设法在我的 PC 上本地运行以下 RMI 示例,而不是通过两台单独的 Linux 机器。
服务器界面:
public interface PowerService extends Remote{
public BigInteger square ( int number )
throws RemoteException;
public BigInteger power ( int num1, int num2)
throws RemoteException;
}
服务器:
public class PowerServiceServer extends UnicastRemoteObject implements
PowerService {
public PowerServiceServer() throws RemoteException {
super();
}
public BigInteger square(int number) throws RemoteException {
imp .....
return (bi);
}
public BigInteger power(int num1, int num2) throws RemoteException {
imp .....
return bi;
}
public static void main(String[] args) throws Exception {
PowerServiceServer svr = new PowerServiceServer();
// ... and bind it with the RMI Registry
Naming.bind("PowerService", svr);
System.out.println("Service bound....");
}
}
客户端:
public class PowerServiceClient {
public static void main(String args[]) throws Exception {
// Call registry for PowerService
PowerService service = (PowerService) Naming.lookup("rmi://" + args[0]
+ "/PowerService");
DataInputStream din = new DataInputStream(System.in);
for (;;) {
System.out.println("1 - Calculate square");
System.out.println("2 - Calculate power");
System.out.println("3 - Exit");
System.out.println();
System.out.print("Choice : ");
String line = din.readLine();
Integer choice = new Integer(line);
int value = choice.intValue();
switch (value) {
case 1:
// Call remote method
....................
break;
case 2:
// Call remote method
....................
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid option");
break;
}
}
}
客户端接口和服务器一样
这是我为了运行 rmi 示例所做的:
1)在服务器端我创建了存根
2) 运行 rmiregisrty
3)运行服务器
4)我将存根从服务器端复制到客户端到同一个包中
5)运行客户端
运行客户端后,我收到以下错误消息:
线程“主”java.rmi.ConnectException 中的异常:连接拒绝主机:127.0.0.1;嵌套异常是:java.net.ConnectException:连接在 sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:601) 在 sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:198) 处被拒绝在 sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:184) 在 sun.rmi.server.UnicastRef.invoke(UnicastRef.java:110) 在 compute.PowerServiceServer_Stub.square(未知来源)
可能是由于某些防火墙我无法连接或者我做错了什么?
谢谢