如何rmi运行java程序?

来源:百度知道 编辑:UC知道 时间:2024/07/04 17:42:59
public class Test {

public void say(){
System.out.println("Hello");
}
public static void main(String[] args) {
Test test = new Test();
test.say();
}
}

怎么用rmi来运行这个程序?rmi怎样配置呢?

首先在server端需要一个接口,继承自java.rmi.Remote

public interface Hello extends Remote {

public void say() throws RemoteException;
}

其次实现这个接口并继承java.rmi.server.UnicastRemoteObject
public class SayHello extends UnicastRemoteObject implements Hello{

protected SayHello() throws RemoteException{
super();
}
public String say() throws RemoteException {
return "Hello";
}
}

接着注册服务,绑定端口

public class Reg {
public static void main(String[] args) throws RemoteException,MalformedURLException{
LocateRegistry.createRegistry(1099);
SayHello sh = new SayHello();
Naming.rebind("rmi://localhost:1099/sh", sh);
System.out.println("注册完毕");
}
}

然后在客户端
public class Client {
public static void main(String[] args) throws RemoteException,MalformedURLException,NotBoundException{
Hello h = (Hello)Naming.look