IHello.java

import java.rmi.Remote;
import java.rmi.RemoteException; public interface IHello extends Remote{
public void say() throws RemoteException;
}

Hello.java

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject; public class Hello extends UnicastRemoteObject implements IHello{ private static final long serialVersionUID = 1L; protected Hello() throws RemoteException {
super();
} @Override
public void say() throws RemoteException {
System.out.println("Hello World");
}
}

HelloServer.java

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.net.MalformedURLException; public class HelloServer { public static void main(String[] args) {
try {
IHello h = new Hello();
LocateRegistry.createRegistry(8888);
Naming.rebind("rmi://localhost:8888/h", h);
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
} }

HelloClient.java

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException; public class HelloClient { public static void main(String[] args) {
try {
IHello h = (IHello) Naming.lookup("rmi://localhost:8888/h");
h.say();
} catch (MalformedURLException | RemoteException | NotBoundException e) {
e.printStackTrace();
} } }

先运行HelloServer类,再运行HelloClient类,即可在Console打印出字符串"Hello World"。

附:其实任何技术的HelloWorld实例都挺有意思的,因为十分地简洁。

05-11 22:35