Java RMI初探

1、    rmi接口声明

package casia.isiteam.plgroup.index.rmi; import java.rmi.Remote; import java.rmi.RemoteException; public interface Hello extends Remote { String sayHello() throws RemoteException; } 

2、    Server端

package casia.isiteam.plgroup.index.rmi; import java.rmi.AlreadyBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; public class Server implements Hello { @Override public String sayHello() { return "Server say hello"; } public static void main(String[] args) { Server obj=new Server(); try { Hello stub=(Hello)UnicastRemoteObject.exportObject(obj,0); Registry registry=LocateRegistry.getRegistry(); registry.bind("hello", stub); System.out.println("Server ready"); } catch (RemoteException e) { e.printStackTrace(); } catch (AlreadyBoundException e) { e.printStackTrace(); } } } 

3、    Client端

package casia.isiteam.plgroup.index.rmi; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class Client { public static void main(String[] args) { String host = args.length < 1 ? null : args[0]; try { Registry registry = LocateRegistry.getRegistry(host); Hello stub = (Hello) registry.lookup("hello"); String response = stub.sayHello(); System.out.println("response: " + response); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } } } 

4、    Unbind解除绑定
如果直接停掉程序,rmi并不会解除对stub的绑定,当再次启动server的时候会出现AlreadyBoundException

package casia.isiteam.plgroup.index.rmi; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class Unbound { /** * @param args */ public static void main(String[] args) { Registry registry; try { registry = LocateRegistry.getRegistry(); registry.unbind("hello"); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotBoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

5、    启动rmi registry
进入jdk/bin目录执行start rmiregistry
6、    Eclipse中启动server端需要配置的地方:在Server的运行参数中设置java.rmi.server.codebase为-Djava.rmi.server.codebase=file:${workspace_loc}/Index/bin/

Java RMI初探_第1张图片

7、    在命令行执行,classpath及java.rmi.server.codebase的设置方法及运行参数(Windows环境)如下:
D:/>java -cp D:/workspace/Index/bin -Djava.rmi.server.codebase=file:D:/workspace
/Index/bin/ casia.isiteam.plgroup.index.rmi.Server

8、    此程序为官方《Getting Started Using JavaTM RMI》一文的实现,地址如下:
http://download.oracle.com/javase/6/docs/technotes/guides/rmi/hello/hello-world.html

 

你可能感兴趣的:(java&jsp,java,server,string,class,interface,eclipse)