RMI,Remote Method Invocation ,远程方法调用,是Java体系中很重要的一个机制,是Enterprise JavaBeans的支柱,是建立分布式Java应用程序的很快捷的方式。RMI非常容易使用的,但是它却非常的强大。
一个正常工作的RMI系统由下面几个部分组成:
* 远程服务的接口定义
* 远程服务接口的具体实现
* Stub 和 Skeleton 文件
* 一个运行远程服务的服务器
* 一个RMI命名服务,它允许客户端去发现这个远程服务
* 类文件的提供者(一个HTTP或者FTP服务器)
* 一个需要这个远程服务的客户端程序
下面写一个最简单的例子,可以在一台电脑上运行服务端,在另一台电脑上运行客户端。
首先定义一个两端共用的接口:
package com.ling.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface IHello extends Remote {
public String sayHello(String str) throws RemoteException;
}
这个接口要继承Remote接口。
写一个服务端:
package com.ling.rmi;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class ServerImpl implements IHello {
protected ServerImpl() throws RemoteException {
super();
}
@Override
public String sayHello(String str) throws RemoteException {
return "Hello,"+str+". this is the server!";
}
public static void main(String[] args) throws RemoteException, AlreadyBoundException {
Registry reg = LocateRegistry.createRegistry(8989);
reg.bind("server", UnicastRemoteObject.exportObject(
new ServerImpl(), 0));
System.err.println("Server Ready!");
}
}
最后 再写一个客户端:
package com.ling.rmi;
import java.rmi.Naming;
public class Client {
public static void main(String args[]) throws Exception {
IHello server = (IHello) Naming.lookup("rmi://localhost:8989/server");
System.out.println(server.sayHello("lingyibin"));
}
}
在两台电脑上运行 试一下,体验一下RMI的强大。。。