- User类
注意:需要实现序列化
1 package study.rmi.server; 2 3 import java.io.Serializable; 4 5 public class User implements Serializable { 6 7 /** 8 * 9 */ 10 private static final long serialVersionUID = 1L; 11 12 private String name; 13 14 public String getName() { 15 return name; 16 } 17 18 public void setName(String name) { 19 this.name = name; 20 } 21 22 23 }
- 接口类
1 package study.rmi.server; 2 3 import java.rmi.Remote; 4 import java.rmi.RemoteException; 5 6 public interface HelloRemote extends Remote{ 7 8 String sayHello(User user) throws RemoteException; 9 }
- 接口实现类
1 package study.rmi.server; 2 3 import java.rmi.RemoteException; 4 import java.rmi.server.UnicastRemoteObject; 5 6 public class HelloRemoteImpl extends UnicastRemoteObject implements HelloRemote { 7 8 private static final long serialVersionUID = 1L; 9 10 protected HelloRemoteImpl() throws RemoteException { 11 super(); 12 } 13 14 @Override 15 public String sayHello(User user) throws RemoteException { 16 return "hello," + user.getName(); 17 } 18 19 }
- rmi服务端类
1 package study.rmi.server; 2 3 import java.net.MalformedURLException; 4 import java.rmi.Naming; 5 import java.rmi.RemoteException; 6 import java.rmi.registry.LocateRegistry; 7 8 public class RemoteServer { 9 10 public static void main(String[] args) { 11 try { 12 LocateRegistry.createRegistry(6666); 13 HelloRemote server = new HelloRemoteImpl(); 14 Naming.rebind("//127.0.0.1:6666/HelloRemote", server); 15 System.out.println("服务端启动"); 16 } catch (RemoteException e) { 17 e.printStackTrace(); 18 } catch (MalformedURLException e) { 19 e.printStackTrace(); 20 } 21 } 22 23 }
- 客户端类
1 package study.rmi.client; 2 3 import java.net.MalformedURLException; 4 import java.rmi.Naming; 5 import java.rmi.NotBoundException; 6 import java.rmi.RemoteException; 7 import study.rmi.server.HelloRemote; 8 import study.rmi.server.User; 9 10 public class RMIClient { 11 12 public static void main(String[] args) { 13 String url = "//127.0.0.1:6666/HelloRemote"; 14 try { 15 HelloRemote helloRemote = (HelloRemote) Naming.lookup(url); 16 User user = new User(); 17 user.setName("zs"); 18 System.out.println(helloRemote.sayHello(user)); 19 } catch (MalformedURLException e) { 20 e.printStackTrace(); 21 } catch (RemoteException e) { 22 e.printStackTrace(); 23 } catch (NotBoundException e) { 24 e.printStackTrace(); 25 } 26 27 } 28 }
可以看看下面介绍java rmi的文章:
http://haolloyin.blog.51cto.com/1177454/332426/
http://www.blogjava.net/orangelizq/archive/2007/12/01/164541.html