RMI示例
理论
实践
View Code
文件1 package DS.homework; import java.rmi.Remote; import java.rmi.RemoteException; public interface Book extends Remote { String getDescription() throws RemoteException; Integer getNumberofStockpile() throws RemoteException; } 文件2 package DS.homework; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class BookImpl extends UnicastRemoteObject implements Book { private static final long serialVersionUID = 1L; private String description; private Integer numberofStockpile; public BookImpl(String description, int numberofStockpile) throws RemoteException { super(); this.description = description; this.numberofStockpile = numberofStockpile; } @Override public String getDescription() throws RemoteException { // TODO Auto-generated method stub return description; } @Override public Integer getNumberofStockpile() throws RemoteException { // TODO Auto-generated method stub return numberofStockpile; } } 文件3 package DS.homework; import java.rmi.Naming; import java.rmi.registry.LocateRegistry; public class Server { public static void main(String[] args) { // TODO Auto-generated method stub try { BookImpl bookService1 = new BookImpl("Distributed System Concepts and Design", 1); BookImpl bookService2 = new BookImpl("Distributed Systems: Principles and Paradigms", 2); // 注册通讯端口 LocateRegistry.createRegistry(6600); // 注册通讯路径 Naming.rebind("rmi://127.0.0.1:6600/ReferenceBook1", bookService1); Naming.rebind("rmi://127.0.0.1:6600/ReferenceBook2", bookService2); System.out.println("Service Start!"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 文件4 package DS.homework; import java.rmi.Naming; public class Client { public static void main(String[] args) { try { // 调用远程对象,注意RMI路径与接口必须与服务器配置一致 System.out.println(Naming.lookup("rmi://127.0.0.1:6600/ReferenceBook1").getClass()); Book book1 = (Book) Naming.lookup("rmi://127.0.0.1:6600/ReferenceBook1"); Book book2 = (Book) Naming.lookup("rmi://127.0.0.1:6600/ReferenceBook2"); System.out.println(book1.getDescription() + ":" + book1.getNumberofStockpile()); System.out.println(book2.getDescription() + ":" + book2.getNumberofStockpile()); } catch (Exception ex) { ex.printStackTrace(); } } }
错误
1、java.lang.ClassCastException: $Proxy0 cannot be cast to DS.homework.BookImpl
at DS.homework.Client.main(Client.java:10)
Client中的类型应该是Book接口,而不是其实现类
2、java.rmi.server.ExportException: remote object implements illegal remote interface; nested exception is: java.lang.IllegalArgumentException: illegal remote method encountered: public abstract java.lang.String DS.homework.Book.getDescription()
remote接口应该抛出异常即
String getDescription() throws RemoteException
而不是
String getDescription()
xxx