2012-07-31 117 views
2

我想在RMI方法中添加參數。當我添加例如String一切工作正常。但我不確定是否可以傳遞我創建的對象。我是新來的RMI所以我的代碼非常簡單:如何在RMI方法中傳遞參數中的對象?

HelloIF

public interface HelloIF extends Remote { 
    String greeting(Context c) throws RemoteException; 
} 

你好

public class Hello extends UnicastRemoteObject implements HelloIF { 

    public Hello() throws RemoteException { 
    } 

    public String greeting(Context c) throws RemoteException { 
     addToContext(c); 
     report(c); 
     return "greeting"; 
    } 

    void addToContext(Context c) { 
     c.addID(Thread.currentThread().getId()); 
    } 

    void report(Context c) { 
     System.out.println("Hello.greeting() thread : " 
       + Thread.currentThread().getName() + " " 
       + Thread.currentThread().getId()); 

     System.out.println("Hello.greeting() context : " 
       + c.getDistributedThreadName() + " " + c.getRequestType()); 
    } 
} 

的RMIServer

public class RMIServer { 

    public static void main(String[] args) throws RemoteException, MalformedURLException { 
     LocateRegistry.createRegistry(1099); 
     HelloIF hello = new Hello(); 
     Naming.rebind("server.Hello", hello); 
     System.out.println("server.RMI Server is ready."); 
     System.out.println("RMIServer.main() thread : " + Thread.currentThread().getName() 
       + " " + Thread.currentThread().getId()); 
    } 
} 

RMIClient

public class RMIClient { 
    public static void main(String[] args) throws RemoteException, MalformedURLException, NotBoundException { 

     Context context = new Context("request1", Thread.currentThread().getName()+System.currentTimeMillis()); 

     Registry registry = LocateRegistry.getRegistry("localhost"); 
     HelloIF hello = (HelloIF) registry.lookup("server.Hello"); 
     System.out.println(hello.greeting(context)); 
     System.out.println("RMIClient.mian() thread : " + Thread.currentThread().getName() 
       + " " + Thread.currentThread().getId()); 
    } 
} 

最後我班語境

public class Context 
{ 
    private String requestType; 
    private String distributedThreadName; 
    private List<Long> IDList; 

    (...) getters/setters 
} 

我應該怎麼做才能讓傳遞上下文的可能嗎?

+0

這裏是按引用傳遞參數的方式: http://stackoverflow.com/questions/11187548/is-it-possible-to-pass-by-reference-in-rmi – dz00dz 2017-03-08 22:09:34

回答

5

你的對象應該實現Serializable。正如我所見,這將是一個問題。這是需要的,因爲兩個部分之間的通信是使用序列化完成的,所以需要將每個對象發送到另一個部分,需要成爲實現Serializable的類的實例。

public class Context implements Serializable 
{ 
    private String requestType; 
    private String distributedThreadName; 
    private List<Long> IDList; 

    (...) getters/setters 
} 

請加上serialVersionUID作爲一個良好的做法。喜歡的東西:

private static final long serialVersionUID = 20120731125400L; 
相關問題