1. RMI Example
Before running RmiServer, rmiregistry.exe must be run from the RmiServer's classes folder. (Example: rmiregistry.exe 5000)
1) RmiInterface.java
1 2 3 4 5 6 | import java.rmi.Remote; import java.rmi.RemoteException; public interface RmiInterface extends Remote { public int add(int a, int b) throws RemoteException; } |
2) RmiServer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; import java.rmi.server.UnicastRemoteObject; public class RmiServer implements RmiInterface { public RmiServer(){} @Override public int add(int a, int b) throws RemoteException { return a+b; } public static void main(String[] args) { RmiServer obj = new RmiServer(); try { RmiInterface stub = (RmiInterface) UnicastRemoteObject.exportObject(obj, 0); Registry registry = LocateRegistry.getRegistry(5000); //default: 1099 registry.rebind("Addition", stub); System.out.println("Server ready"); } catch (Exception e) { e.printStackTrace(); } } } |
3) RmiClient.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class RmiClient { private RmiClient() {} static void testRmiClient() { try { Registry registry = LocateRegistry.getRegistry("127.0.0.1",5000); RmiInterface stub = (RmiInterface) registry.lookup("Addition"); int response = stub.add(1,2); System.out.println("response: " + response); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { testRmiClient(); } } |
댓글 없음:
댓글 쓰기