服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java rmi 简单示例


  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,成功调用.

扫描关注微信公众号