Спасибо большое Domestic Cat за предоставленную информациюInterface Hello: Код | import java.rmi.Remote; import java.rmi.RemoteException;
public interface Hello extends Remote { public String helloWorld () throws RemoteException; }
|
class HelloImpl Код | import java.rmi.server.UnicastRemoteObject; import java.rmi.RemoteException;
public class HelloImpl extends UnicastRemoteObject implements Hello { public HelloImpl() throws RemoteException { // empty but must throw RemoteException } public String helloWorld () throws RemoteException { return "Hello world"; } }
|
class Server Код | import java.rmi.Naming; import java.rmi.server.UnicastRemoteObject; import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; import java.rmi.RemoteException; import java.rmi.NotBoundException;
public class Server { private static final String SERVER_NAME = "Server"; private static final String HOST = "localhost"; private String port; public Server(String port) { this.port = port; } public void runServer() throws IllegalArgumentException, NotBoundException, RemoteException { HelloImpl helloImpl = new HelloImpl(); Registry registry = LocateRegistry.createRegistry(Integer.parseInt(port, 10)); String url = "//" + HOST + ":" + port + "/" + SERVER_NAME; registry.rebind(SERVER_NAME, helloImpl); } }
|
Class Start Код | import java.rmi.Naming; import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; import java.rmi.RemoteException; import java.rmi.NotBoundException;
public class Start { public static final String SERVER_NAME = "Server"; // use : server <port> - start server // client <host> <port> - start client public static void main (String[] args) throws Exception { if (args[0].equals("server")) { Server server = new Server(args[1]); server.runServer(); System.out.println("Server started on port " + args[1]); } else { String lookupString = "//" + args[1] + ":" + args[2] + "/" + SERVER_NAME; Hello hello = (Hello) Naming.lookup(lookupString); System.out.println("RMI object found"); System.out.println(hello.helloWorld()); } } }
|
1. javac *.java 2. rmic HelloImpl (получатся 2 файла - _stub i _skel) 3. Запустить сервер: java Start server 2000 // любой порт > 1023 4. Во второй JVM запустить клиента: java Start client xxx.xxx.xxx.xxx 2000 // ваш хост Учтите, что через файервол это работать не будет (скорее всего), если не открыт соответствующий порт.
|