public interface HelloRemote extends Remote{
public void sayHello() throws RemoteException;
}
public class HelloImpl extends UnicastRemoteObject implements HelloRemote{ public HelloImpl() throws RemoteException { super(); } public void sayHello() throws RemoteException { System.out.println("Hello World!"); } }
public class RMIServer { public static void main(String[] args) throws RemoteException, MalformedURLException { HelloRemote hello=new HelloImpl(); Naming.rebind("hello", hello); } }
public class RMIClient { public static void main(String args[]) throws MalformedURLException, RemoteException, NotBoundException{ System.setSecurityManager(new RMISecurityManager());//如果服务器和客户端不再同一台机器要加这行 HelloRemote hello=(HelloRemote) Naming.lookup("hello"); hello.sayHello(); } }
package RMITest; import java.rmi.Remote; import java.rmi.RemoteException; public interface Example extends Remote { public void setString( String s ) throws RemoteException; public String getString() throws RemoteException; }
package RMITest; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class ExampleServer extends UnicastRemoteObject implements Example { private String stringState; public ExampleServer() throws RemoteException {} @Override public void setString(String s) throws RemoteException { // TODO Auto-generated method stub stringState = s; } @Override public String getString() throws RemoteException { // TODO Auto-generated method stub return stringState; } }
import java.rmi.registry.LocateRegistry; public class Server { /** * @param args * @throws MalformedURLException * @throws RemoteException */ public static void main(String[] args) throws RemoteException, MalformedURLException { // TODO Auto-generated method stub LocateRegistry.createRegistry(8889); ExampleServer es = new ExampleServer(); Naming.rebind("rmi://localhost:8889/Example", es); } }
package RMITest; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; public class ExampleClient { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { Example example = (Example) Naming.lookup("rmi://localhost:8889/Example"); example.setString("success"); System.out.println(example.getString()); } catch (MalformedURLException | RemoteException | NotBoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }