1、 相关类
package com.rmijava.test;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* 定义一个远程接口,必须继承Remote接口,其中需要远程调用的方法必须抛出RemoteException异常
* @author Administrator
*
*/
public interface Hello extends Remote{
public String helloWorld() throws RemoteException;
}
package com.rmijava.test;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class HelloImpl extends UnicastRemoteObject implements Hello{
/**
* 因为UnicastRemoteObject的构造方法抛出了RemoteException异常,因此这里默认的构造方法必须写,必须声明抛出RemoteException异常
* @throws RemoteException
*/
protected HelloImpl() throws RemoteException {
}
@Override
public String helloWorld() throws RemoteException {
return "Hello World!";
}
}
2、服务端
package com.rmijava.test;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
public class Server {
//获取服务器ip
private static String rmiHost = "127.0.0.1";
//获取端口
private static String rmiPort = "8888";
public static void main(String[] args) throws Exception{
Hello hello = new HelloImpl();
String bindName = "rmi://" + rmiHost + ":" + rmiPort + "/";
LocateRegistry.createRegistry(8888);
Naming.bind(bindName + "hello", hello);
String[] strs = Naming.list(bindName);
for(String str : strs){
System.out.println(str);
}
}
}
3、客户端
package com.rmijava.test;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class Client {
public static void main(String[] args) throws RemoteException, MalformedURLException, NotBoundException {
Hello helloImpl = (Hello) Naming.lookup("rmi://localhost:8888/hello");
System.out.println(helloImpl.helloWorld());
}
}