1. 新建Handler类
import java.rmi.Remote;
import java.rmi.RemoteException;
//定义一个远程接口,必须继承Remote接口,
//其中需要远程调用的方法必须抛出RemoteException异常
public interface Handler extends Remote {
public String hello(String name) throws RemoteException;
}
2. 新建HandlerImpl类, 是Handler的实现;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
//需要继承UnicastRemoteObject类
public class HandlerImpl extends UnicastRemoteObject implements Handler {
private static final long serialVersionUID = 1L;
protected HandlerImpl() throws RemoteException {
super();
}
@Override
public String hello(String msg) throws RemoteException {
return "你好"+msg;
}
}
3. 注册并启动服务
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
public class HandlerServer {
public static void main(String[] args) {
try {
Handler handler = new HandlerImpl();
// 本地主机上的远程对象注册表Registry的实例,并指定端口为8888,
//这一步必不可少(Java默认端口是1099),必不可缺的一步,缺少注册表创建,
//则无法绑定对象到远程注册表上
LocateRegistry.createRegistry(8888);
// 把远程对象注册到RMI注册服务器上,并命名为handler
Naming.bind("rmi://localhost:8888/handler", handler);
System.out.println("远程Handler对象绑定成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. 测试类
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class HandlerClient {
public static void main(String[] args) {
try {
Handler rHello = (Handler)Naming.lookup("rmi://localhost:8888/handler");
System.out.println(rHello.hello("张三"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
}
Java rmi应用
最新推荐文章于 2024-09-29 14:23:34 发布