十分钟学会JavaRMI

RMI是Java平台实现远程调用的规范,下面是一个小例子,本机测试通过

一共有三个java类,远程接口,服务端程序,客户端程序

远程接口:

import java.rmi.*;public interface HelloIn extends java.rmi.Remote{  String sayHello() throws RemoteException;}

服务端程序:

/*** author by http://www.bt285.cn  http://www.5a520.cn*/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

客户端程序:

/*** author by http://www.bt285.cn  http://www.5a520.cn*/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,成功调用.

同生天地间,为何我不能。

十分钟学会JavaRMI

相关文章:

你感兴趣的文章:

标签云: