创建接口
/**
* 定义一个远程接口,必须继承Remote接口
*/
public interface HelloService extends Remote
{
/**
* 需要远程调用的方法必须抛出RemoteException异常
* @param msg
* @return
* @throws RemoteException
*/
String sayHello(String msg) throws RemoteException;
}
2.创建实现类
/**
* 远程的接口的实现.
*/
public class HelloServiceImpl extends UnicastRemoteObject implements HelloService
{
/**
* 因为UnicastRemoteObject的构造方法抛出了RemoteException异常,
* 因此这里默认的构造方法必须写,必须声明抛出RemoteException异常
* @throws RemoteException
*/
public HelloServiceImpl() throws RemoteException {
}
/**
* 业务实现方法
* @param msg
* @return
* @throws RemoteException
*/
public String sayHello(String msg) throws RemoteException {
return "server received the msg : " + msg;
}
}
3.创建启动服务
/**
* 创建RMI注册表,
* 启动RMI服务,
* 并将远程对象注册到RMI注册表中。
*/
public class HelloServer
{
public static void main(String[] args)
{
try
{
//创建一个远程对象
HelloService helloService = new HelloServiceImpl();
//本地主机上的远程对象注册表Registry的实例,并指定端口为8888.
// 这一步必不可少(Java默认端口是1099),必不可缺的一步.
// 缺少注册表创建,则无法绑定对象到远程注册表上
LocateRegistry.createRegistry(9123);
//把远程对象注册到RMI注册服务器上,并命名为hello
//绑定的URL标准格式为:rmi://host:port/name(其中协议名可以省略)
Naming.bind("rmi://localhost:9123/hello", helloService);
System.err.println("==========远程对象绑定成功============");
} catch (RemoteException e) {
System.err.println("创建远程对象发生异常!");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("发生URL畸形异常!");
e.printStackTrace();
} catch (AlreadyBoundException e) {
System.out.println("发生重复绑定对象异常!");
e.printStackTrace();
}
}
}
4.创建客户端
/**
* 在客户端调用远程对象上的远程方法
*/
public class HelloClient
{
public static void main(String[] args)
{
try
{
//在RMI服务注册表中查找名称为helloService的对象,并调用其上的方法
HelloService helloService
=(HelloService) Naming.lookup("rmi://localhost:9123/hello");
System.out.println(helloService.sayHello("测试"));
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
注:RMI要求服务端和客户端的编写语言都是java.如果需要跨语言,则建议使用webservice.
参考地址:http://docs.oracle.com/javase/6/docs/technotes/guides/rmi/hello/hello-world.html
转载于:https://blog.51cto.com/881206524/1922761