2013-07-21 21 views
0

什麼問題用下面的代碼...... 我有這個Complex類:.NET遠程和服務器激活的對象

public class Complex : MarshalByRefObject 
    { 

     public double imaginary{get;set;} 
     public double real{get;set;}    

     public void setReal(double re) 
     { 
      real = re; 
     } 

     public void setImaginary(double im) 
     { 
      imaginary = im; 
     } 

     public Complex(double im, double re) 
     { 
      imaginary = im; 
      real = re; 
     }  

     public void writeMembers() 
     { 
      Console.WriteLine(real.ToString() + imaginary.ToString()); 
     } 
    } 

其實,還有更多了一點,但它的代碼太大,而我們在這方面並沒有使用它的其餘部分。

然後,我實現了一個偵聽連接的服務器:

HttpChannel channel = new HttpChannel(12345);     
      ChannelServices.RegisterChannel(channel, false); 
      RemotingConfiguration.RegisterWellKnownServiceType(typeof(SharedLib.Complex), "ComplexURI", WellKnownObjectMode.SingleCall); 

      Console.WriteLine("Server started. Press any key to close..."); 
      Console.ReadKey(); 

      foreach (IChannel ichannel in ChannelServices.RegisteredChannels) 
      { 
       (ichannel as HttpChannel).StopListening(null); 
       ChannelServices.UnregisterChannel(ichannel); 
      } 

然後,我們在客戶端:

try 
      { 
       HttpChannel channel = new HttpChannel(); 
       RemotingConfiguration.Configure("Client.exe.config", false); 

       Complex c1 = (Complex)Activator.GetObject(typeof(Complex), "http://localhost:12345/ComplexURI");      


       if (RemotingServices.IsTransparentProxy(c1)) 
       { 
        c1.real = 4; 
        c1.imaginary = 5;  

        c1.writeMembers();      

        Console.ReadLine(); 
       } 
       else 
       { 
        Console.WriteLine("The proxy is not transparent"); 
       } 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
       Console.ReadLine(); 
      } 
     } 

然後,我運行服務器,這將打開一個控制檯窗口,我運行客戶端。 而不是在服務器窗口中顯示4和5,我只是得到00,這是一個表示成員沒有改變的標誌。 我該怎麼做,所以會員變更? 謝謝。

回答

1

問題是,您正在使用WellKnownObjectMode.SingleCall。作爲the documentation說:

  • SingleCall每一個進來的消息是由一個新的對象實例提供服務。
  • 單身每個傳入消息都由相同的對象實例提供服務。也

見用於RegisterWellKnownServiceType的文檔:

當呼叫到達服務器,.NET框架從所述消息中提取URI,檢查遠程處理表中查找用於所述參考對象匹配URI,然後在必要時實例化對象,將方法調用轉發給對象。 如果對象註冊爲SingleCall,則在方法調用完成後它將被銷燬。爲每個調用的方法創建一個新的對象實例。

在你的情況,聲明c.Real = 4是對Real屬性setter的調用。它調用遠程對象,該對象創建一個新對象,將Real屬性設置爲4,然後返回。然後,當您設置imaginary屬性時,它會創建一個新對象等。

如果要使用此功能,您必須使用WellKnownObjectMode.Singleton。但你可能想問自己,你是否真的想要這樣一個「健談」的界面。每次設置屬性時,都需要通過代理向服務器進行調用。

最後,您可能會考慮完全放棄Remoting。這是舊技術,並有一些缺點。如果這是新開發,則應使用Windows Communications Foundation(WCF)。 Remoting documentation說:

本主題特定於舊版技術,該技術爲保持與現有應用程序的向後兼容性,不建議用於新開發。現在應該使用Windows Communication Foundation(WCF)開發分佈式應用程序。

相關問題