ct的对象A,把对象A 传递到服务器端,这个时候服务器端得到的只是对象A的引用,如果服务器调用对象A的方法 ,这个方法就会在客户端执行。
下面的例子说明了这一点,我们定义IRefWorker接口和RefWorkerImp类,在客户端创建 RefWorkerImp类的对象,把该对象传递到服务器端,服务器端调用该对象的方法,你会发现 该方法在客户端执行。
IRefWorker.java
1package rmistudy;
2
3import java.rmi.Remote;
4import java.rmi.RemoteException;
5
6public interface IRefWorker extends Remote {
7 public void work() throws RemoteException;
8}
RefWorkerImp.java
1package rmistudy;
2
3import java.rmi.RemoteException;
4import java.rmi.server.RMIClientSocketFactory;
5import java.rmi.server.RMIServerSocketFactory;
6import java.rmi.server.UnicastRemoteObject;
7
8public class RefWorkerImp extends UnicastRemoteObject implements IRefWorker {
9
10 public RefWorkerImp() throws RemoteException {
11 super();
12 }
13
14 public void work() throws RemoteException {
15 System.out.println("该方法在服务器端调用,在客户端执行。");
16 }
17
18}
IServer.java
1package rmistudy;
2
3import java.rmi.Remote;
4import java.rmi.RemoteException;
5
6public interface IServer extends Remote {
7 public void doSomeThing() throws RemoteException;
8 public String doSomeThing(ISerializableWorker wk) throws RemoteException;
9 public void doSomeThing(IRefWorker wk) throws RemoteException;
10}
简单理解RMI(8)
时间:2011-04-13 海边沫沫
ServerImp.java
该类中实现接口中定义的方法,和前面的代码相比,多了如下一行
1public void doSomeThing(IRefWorker wk) throws RemoteException{
2 wk.work();
3 }
Client.java
1package rmistudy;
2
3import java.rmi.*;
4
5public class Client {
6
7 /** *//**
8 * @param args
9 */
10 public static void main(String[] args) {
11 IServer server = null;
12
13 try{
14 server = (IServer)Naming.lookup("//localhost/MyServer");
15 System.out.println("查找远程对象成功。");
16 }catch(Exception e){
17 System.out.println("查找远程对象失败:");
18 System.out.println(e.getMessage());
19 System.exit(0);
20 }
21
22 try{
23 server.doSomeThing();
24 System.out.println("调用doSomeThing()成功。");
25 String str = server.doSomeThing(new SerializableWorkerImp());
26 System.out.println("调用带序列化参数的doSomeThing()成功");
27 System.out.println("从服务器端返回的字符串:"+str);
28 server.doSomeThing(new RefWorkerImp());
29 System.out.println("调用带引用参数的doSomeThing()成功");
30 }catch(Exception e){
31 System.out.println("调用doSomeThing()失败:");
32 System.out.println(e.getMessage());
33 System.exit(0);
34 }
35
36 }
37
38}
程序的运行方法同前,不再重复。
简单理解RMI(9)
时间:2011-04-13 海边沫沫
三、安全管理与授权策略
前面提到过,前面的示例代码,如果真 |