步骤:
1.自定义 创建 java interface 类 并且继承 Remote (接口类命名随意)
public interface RMethod extends Remote {
String sayHello() throws RemoteException;
}
-
创建实现类 RMethodImpl 实现自定义接口类里面的抽象方法 并且继承 UnicastRemoteObject
public class RMethodImpl extends UnicastRemoteObject implements RMethod { private static final long serialVersionUID = 1L; protected RMethodImpl() throws RemoteException { super(); } @Override public String sayHello() throws RemoteException { return "I am test."; } }
注意:
private static final long serialVersionUID = 1L 必须加
构造函数也必须加 super();也加上 -
服务端测试代码
public class Server { static int PORT = 9999;// 端口 static String SERVER_IP = "172.16.0.89";// IP地址 static String OBJECT_NAME = "test";// 绑定名字 public static void main(String[] args) { try { System.setProperty("java.rmi.server.hostname", "172.16.0.89");// 绑定自己的IP LocateRegistry.createRegistry(PORT); RMethod rm = new RMethodImpl(); String objAddr = "rmi://" + SERVER_IP + ":" + PORT + "/" + OBJECT_NAME; Context context = new InitialContext(); context.rebind(objAddr, rm); System.out.println("Server is running..."); } catch (Exception e) { System.out.println("Server startup failed!"); e.printStackTrace(); } } }
4.客户端测试代码
public class C {
public static void main(String[] args) {
RMethod rMethod;
try {
rMethod = (RMethod)Naming.lookup("//172.16.0.74:9999/test");
System.out.println(rMethod.sayHello());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
}
5.注意事项
- 测试端接口类的位置(类全名得一样)
- 安全组件问题 (先别加安全组件了 把RMI玩起来再说)
System.setSecurityManager(new SecurityManager());
rmi.policy
网友评论