RMI例程
- 定义远程接口:扩展java.rmi.Remote;
- 实现远程接口:扩展java.rmi.RemoteServer或它的一个子类,然后实现一个或多个远程接口;
- 生成Stub和Skeleton:rmic <包限定的类名>;(java2以后,skeleton就不用了)
- 注册对象:
- 编写客户端程序:
- policy文件:
远程接口:(HelloInterface.java)
public interface HelloInterface extends java.rmi.Remote {
public String sayHello() throws java.rmi.RemoteException;
}
远程接口实现:(HelloServer.java)
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
import java.util.Date;
public class HelloServer extends UnicastRemoteObject implements HelloInterface {
public HelloServer() throws RemoteException {
super();
}
public String sayHello(){
return "Hello World, the current system time is " + new Date();
}
}
生成Stub和Skeleton:
rmic HelloServer
注册远程对象:(RegisterIt.java)
import java.rmi.*;
public class RegisterIt {
public static void main(String args[]) {
try {
HelloServer obj = new HelloServer();
System.out.println("Object instantiated " + obj);
Naming.rebind("/HelloServer", obj);
System.out.println("HelloServer bound in registry.");
} catch (Exception e) {
System.out.println(e);
}
}
}
编写客户端程序:(HelloClient.java)
import java.rmi.*;
import java.lang.*;

public class HelloClient {
public static void main(String args[]) {
if(System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
HelloInterface obj = (HelloInterface) Naming.lookup("/HelloServer");
String message = obj.sayHello();
System.out.println(message);
} catch (Exception e) {
System.out.println("HelloClient exception: " + e);
}
}
}
编译:
javac *.java
启动rmi服务器:
rmiregistry
注册对象:
java -Djava.security.policy=RegistryIt.policy RegisterIt
运行客户端:
java -Djava.security.policy=RegistryIt.policy HelloClient


浙公网安备 33010602011771号