RMI(Remote Method Invocation)
RMI是分布式对象软件包,它简化了在多台计算机上的JAVA应用之间的通信。
public interface Fibonacci extends Remote {
public BigInteger getFibonacci(int n) throws RemoteException;
public BigInteger getFibonacce(BigInteger n) throws RemoteException;
}
public class FibonacciImpl extends UnicastRemoteObject implements Fibonacci {
public FibonacciImpl() throws RemoteException{
super();
}
public BigInteger getFibonacci(int n) throws RemoteException{
return this.getFibonacce(new BigInteger(Long.toString(n)));
}
public BigInteger getFibonacce(BigInteger n) throws RemoteException {
System.out.println("Calculating the" + n +"th Fibonacci number");
BigInteger zero = new BigInteger("0");
BigInteger one = new BigInteger("1");
if(n.equals(zero)) return one;
if(n.equals(one)) return one;
BigInteger i = one;
BigInteger low = one;
BigInteger high = one;
while(i.compareTo(n) == -1){
BigInteger temp = high;
high = high.add(low);
low = temp;
i = i.add(one);
}
return high;
}
}
public class FibonacciServer {
//服务器启动
public static void main(String[] args) {
try {
//加载安全管理器
//System.setSecurityManager(new RMISecurityManager() );
System.out.println("begin 1");
FibonacciImpl f = new FibonacciImpl();
Naming.rebind("fibonacci", f);
System.out.println("Fibonacci Server ready.");
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
}
}
public class FibonacciClient {
/**
* @param args客户端
*/
public static void main(String[] args) {
String rmiUrl = "rmi://localhost/fibonacci";
BigInteger index = new BigInteger("30");
try {
Object o = Naming.lookup(rmiUrl);
Fibonacci calculator = (Fibonacci)o;
BigInteger f = calculator.getFibonacce(index);
System.out.println("The " + index + "th Fibonacci number is "+ f);
} catch (Exception e) {
e.printStackTrace();
}
}
}
复制以上代码到Eclipse,按如下步骤操作:
1、编译桩: 在windows中,在DOS提示符下运行 rmic 包.FibonacciImpl
2、确保所有桩和服务器类位于服务器的类路径中。
3、在windows中,要在DOS提示符下启动注册表,如下:C:\start rmiregistry
4、运行FibonacciServer 和 FibonacciClient 即可