rmi是java平台实现远程调用的规范,下面是一个小例子,本机测试通过
一共有三个java类,远程接口,服务端程序,客户端程序
远程接口:
import java.rmi.*;
public interface helloin extends java.rmi.remote{
string sayhello() throws remoteexception;
}
服务端程序:
import java.rmi.*;
import java.net.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class hello extends java.rmi.server.unicastremoteobject implements helloin{
public hello() throws remoteexception{
super();
}
public string sayhello() throws remoteexception{
return "hello,world!";
}
public static void main(string[] args){
//system.setsecuritymanager(new java.rmi.rmisecuritymanager());
try{
hello h=new hello();
java.rmi.naming.rebind("hello",h);
system.out.print("ready......");
}
catch(exception e){
e.printstacktrace();
}
}
}
执行服务端程序前在命令行方式下启动rmi的注册程序: start rmiregistry
客户端程序:
import java.rmi.*;
import java.rmi.registry.*;
public class helloworld{
public static void main(string[] args){
//system.setproperty( "java.security.policy", "client.policy" );
//system.setsecuritymanager(new java.rmi.rmisecuritymanager());
try{
helloin hi=(helloin)naming.lookup("//fengl/hello");
for(int i=0;i<10;i++){
system.out.println(hi.sayhello());
}
}
catch(exception e){
e.printstacktrace();
}
}
}
执行客户端程序前先用 rmic hello 生成stub 和 skeleton 的class,它们
实际上是远程调用的底层的实现。
最后执行java helloworld 控制台打印出 hello,world,成功调用.
闽公网安备 35060202000074号