【Java Web开发学习】远程方法调用RMI

Java RMI 远程方法调用Remote Method Invocation

转载:http://www.cnblogs.com/yangchongxing/p/9078061.html

1、创建远程方法接口(必须继承自java.rmi.Remote接口)

package cn.ycx.date;

import java.rmi.Remote;
import java.rmi.RemoteException; public interface DateRemote extends Remote {
public String now() throws RemoteException;
}

2、创建远程服务实现

远程对象必须实现java.rmi.server.UniCastRemoteObject类,该类的构造函数中将生成stub(存根)和skeleton(骨架), 这样才能保证客户端访问获得远程对象时,该远程对象将会把自身的一个拷贝以Socket的形式传输给客户端,此时客户端所获得的这个拷贝称为Stub(存根),而服务器端本身已存在的远程对象则称之为Skeleton(骨架)。其实此时的存根是客户端的一个代理,用于与服务器端的通信,  而骨架也可认为是服务器端的一个代理,用于接收客户端的请求之后调用远程方法来响应客户端的请求。

package cn.ycx.server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.text.SimpleDateFormat;
import java.util.Date; import cn.ycx.date.DateRemote; public class DateRemoteImpl extends UnicastRemoteObject implements DateRemote {
private static final long serialVersionUID = -4892445365627614558L;
protected DateRemoteImpl() throws RemoteException {
super();
}
@Override
public String now() throws RemoteException {
SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
return format.format(new Date());
}
}

3、启动远程服务

package cn.ycx.server;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
// java cn.ycx.server.ServerTest
public class ServerTest {
//rmiregistry
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.createRegistry(1099);
registry.bind("dateRemote", new DateRemoteImpl());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("RMI Server is ready...");
}
}

4、创建客户端实现

package cn.ycx.client;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException; import cn.ycx.date.DateRemote; // java -jar client.jar
public class ClientTest { public static void main(String[] args) {
DateRemote dateRemote;
try {
dateRemote = (DateRemote) Naming.lookup("rmi://192.168.1.190:1099/dateRemote");//
System.out.println(dateRemote.now());
} catch (MalformedURLException e) {
} catch (RemoteException e) {
} catch (NotBoundException e) {
}
}
}

导出为可执行jar

java -jar client.jar

运行结果:2018-05-23 17:26:58

上一篇:[转]Java远程方法调用


下一篇:mysql导出excel文件的几种方法