我正在学习 Java RMI,并且创建了一个非常简单的服务器来计算斐波那契数。服务器(FibonacciServer)创建一个负责计算序列(Fibonacci)的对象,并且该对象实现一个接口(IFibonacci):
FibonacciServer.java:
package myrmifibonacciserver;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
public class FibonacciServer {
public static void main(String args[]){
try{
Fibonacci fib = new Fibonacci();
Naming.rebind("fibonacci", fib);
System.out.println("Fibonacci Server ready.");
}catch(RemoteException rex){
System.err.println("Exception in Fibonacci.main " + rex);
} catch (MalformedURLException ex) {
System.err.println("MalformedURLException " + ex);
}
}
}
斐波那契:
package myrmifibonacciserver;
import java.math.BigInteger;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Fibonacci extends UnicastRemoteObject implements IFibonacci{
private static final long serialVersionUID = -4300545841720809981L;
public Fibonacci() throws RemoteException{
super();
}
@Override
public BigInteger getFibonacci(int n) throws RemoteException {
return getFibonacci(new BigInteger(Long.toString(n)));
}
@Override
public BigInteger getFibonacci(BigInteger n) throws RemoteException {
System.out.println("Calculating teh " + n + "th Fibonacci number");
BigInteger zero = BigInteger.ZERO;
BigInteger one = BigInteger.ONE;
if(n.equals(zero) || n.equals(one))
return one;
BigInteger current = one;
BigInteger low = one;
BigInteger high = one;
BigInteger temp;
while(current.compareTo(n) == -1){
temp = high;
high = high.add(low);
low = temp;
current = current.add(one);
}
return high;
}
}
斐波那契:
package myrmifibonacciserver;
import java.math.BigInteger;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface IFibonacci extends Remote{
public BigInteger getFibonacci(int n) throws RemoteException;
public BigInteger getFibonacci(BigInteger n) throws RemoteException;
}
正如您所看到的,这是一个非常基本的示例。我正在使用以下命令在 Linux 上启动 RMI 注册表rmiregistry &
它启动没有问题。
但是,当我单击运行按钮(在 Eclipse 或 Netbeans 中)来运行我的小项目时,出现错误:
Exception in Fibonacci.main java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: myrmifibonacciserver.IFibonacci
我不知道为什么!
起初我以为这是因为存根,但由于我使用的是 java 1.7,所以这些存根是自动创建的。我究竟做错了什么 ?