java - rmi - 如何将Object(或代码的某些部分)从服务器传递到客户端并在客户端执行它

时间:2016-06-28 18:16:31

标签: java rmi

我有一个使用rmi的服务器/客户端应用程序。这是它的代码:

客户端

public class LightBulbClient{

    public static void main(String args[]){
        try{
            RMILightBulb bulbService = (RMILightBulb) Naming.lookup ( "rmi://192.168.1.2/RMILightBulb" );
            Word w=bulbService.on();
            System.out.println(w.doSomething());
        }
        catch(NotBoundException nbe){nbe.printStackTrace();}
        catch(RemoteException re){re.printStackTrace();}
        catch(Exception e){e.printStackTrace();}
    }
}

////// RMILightBulb界面

public interface RMILightBulb extends Remote{
    public Word on () throws RemoteException;
}

////// RMILightBulbImpl class

public class RMILightBulbImpl extends UnicastRemoteObject implements RMILightBulb, Serializable{
    private boolean lightOn=false;

    public Word on() throws RemoteException{
        lightOn=true;
        return new Word();
    }
}

//////

public class Word implements Serializable {

    private static final long serialVersionUID = 6529685098267757690L;

    public int doSomething(){
        return 0;
    }
}

服务器端代码

public class LightBulbServer{

    public static void main(String args[]){

         try{          
               RMILightBulbImpl bulbService = new RMILightBulbImpl(); 
               Naming.rebind( "rmi://192.168.1.2/RMILightBulb", bulbService ); 
         }
         catch (RemoteException re){re.printStackTrace();}          
         catch (Exception e) {e.printStackTrace();}          
    }
}

RMILightBulb接口和RMILightBulbImpl类与客户端相同。和类Word有一些变化

public class Word implements Serializable {

    private static final long serialVersionUID = 6529685098267757690L;

    public int doSomething(){
        return 2;//on client side this method returns 0;
    }
}

当你注意到客户端新的Word()。doSomething()返回0并且服务器新的Word()。doSomething()返回2;

当我执行此代码客户端打印我0.我应该怎么做新的Word()。doSomething()在客户端打印2;

所以这个问题是我如何在客户端执行服务器代码而不在客户端编写?

任何有用的帮助!

如果任何其他技术可以执行此操作,请告诉我们!

0 个答案:

没有答案