HeadFirst设计模式之RMI介绍
一、使用步骤
1.generate stubs and skeletons:Run rmic on the remote implementation class
如:D:\Workspaces\MyEclipse10\HeadFirstDesignPattern\bin>rmic headfirst.designpatterns.rmi.MyRemoteImpl
2.Bring up a terminal and start the rmiregistry
例如:D:\Workspaces\MyEclipse10\HeadFirstDesignPattern\bin>rmiregistry
3.start the service:Bring up another terminal and start your service
在MyEclipse中执行service的main方法
4.执行client的main方法
二、代码实现
1.
1 package headfirst.designpatterns.rmi; 2 3 import java.rmi.*; 4 public interface MyRemote extends Remote { 5 public String sayHello() throws RemoteException; 6 }
2.
1 package headfirst.designpatterns.rmi; 2 3 import java.rmi.*; 4 import java.rmi.server.*; 5 6 //Extending UnicastRemoteObject is the 7 public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote { 8 //Be sure arguments and return values are primitives or Serializable 9 public String sayHello() { 10 return "Server says, ‘Hey’"; 11 } 12 13 public MyRemoteImpl() throws RemoteException {} 14 15 public static void main(String[] args) { 16 try { 17 MyRemote service = new MyRemoteImpl(); 18 Naming.rebind("RemoteHello", service); 19 } catch (Exception ex) { 20 ex.printStackTrace(); 21 } 22 } 23 }
3.
1 package headfirst.designpatterns.rmi; 2 3 import java.rmi.*; 4 5 public class MyRemoteClient { 6 public static void main(String[] args) { 7 new MyRemoteClient().go(); 8 } 9 10 public void go() { 11 try { 12 MyRemote service = (MyRemote) Naming.lookup("rmi://127.0.0.1/RemoteHello"); 13 String s = service.sayHello(); System.out.println(s); 14 }catch (Exception ex) { 15 ex.printStackTrace(); 16 } 17 } 18 }
三、结果
You can do anything you set your mind to, man!