要实现java RMI,需要有以下几个步骤:
1、生成一个远程接口
2、实现远程对象(服务器端程序)
3、编写服务器程序
4、编写客户程序
5、注册远程对象
6、调用远程对象
下面以一个简单计算器的实例说明:
1、生成一个远程接口
import java.rmi.Remote;
import java.rmi.RemoteException;//接口必须继承自java.rmi.Remote;
public interface ICalculator extends Remote { //声明接口方法,每一个远程调用方法必须抛出java.rmi.RemoteException异常 public float add(float a,float b) throws RemoteException; public float sub(float a,float b) throws RemoteException; public float mult(float a,float b) throws RemoteException; public float divide(float a,float b) throws RemoteException;}2、实现远程对象(服务器端程序)
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
//服务实现类必须继承自import java.rmi.server.UnicastRemoteObject;
public class CalculatorImpl extends UnicastRemoteObject implements ICalculator {public CalculatorImpl() throws RemoteException{
super(); } @Override public float add(float a, float b) throws RemoteException { // TODO Auto-generated method stub return a + b; }@Override
public float sub(float a, float b) throws RemoteException { // TODO Auto-generated method stub return a - b; }@Override
public float mult(float a, float b) throws RemoteException { // TODO Auto-generated method stub return a*b; }@Override
public float divide(float a, float b) throws RemoteException { // TODO Auto-generated method stub return a/b; }}3、编写服务器程序
import javax.naming.InitialContext;
public class CalcServer {
public static void main(String[] args){ try { CalculatorImpl cal = new CalculatorImpl(); javax.naming.Context context = new InitialContext(); context.bind("rmi://localhost:1099/CalculatorService", cal); System.out.println("server started..."); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }}4、编写客户程序
import javax.naming.Context;
import javax.naming.InitialContext; public class CalcClient { public static void main(String[] args){ try { Context context = new InitialContext(); //查找远程对象并调用远程方法 ICalculator cal = (ICalculator)context.lookup("rmi://localhost:1099/CalculatorService"); System.out.println(cal.add(1, 2)); System.out.println(cal.sub(1, 2)); System.out.println(cal.mult(1, 2)); System.out.println(cal.divide(1, 2)); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }} 5、注册远程对象打开命令提示符,启动rmi注册程序:start rmiregistry回车,将弹出一个rmiregistry.exe窗口。
切换到.class文件所在的目录,注册并启动远程对象:java CalcServer
将打印server started...
6、调用远程对象
打开命令提示符,切换到.class文件所在的目录,调用客户端程序java CalcClient,将打印如下内容:
3.0
-1.0
2.0
0.5