共用方式為


遠端處理範例:存留期

下列程式碼範例示範數個存留使用期案例。CAOClient.exe 會註冊發起者,而在初始使用期後,這個發起者會在與遠端型別中所指定之時間的不同時間更新使用期。請注意,MyClientSponsor 會擴充 MarshalByRefObject 以傳址方式傳遞給遠端使用期管理員;如果沒有擴充,但卻使用 SerializableAttribute 屬性,則會以傳值方式傳遞發起者,並以一般方式執行該發起者,但卻是在伺服器應用程式定義域內執行。

這個應用程式可在單一電腦上或跨網路執行。如果想要透過網路執行這個應用程式,則必須將用戶端組態中的 "localhost" 取代為遠端電腦的名稱。

這個範例使用以 Visual Basic 和 C# 撰寫的程式碼。其中會提供 RemoteType.csCAOClient.cs,但指定的命令列不會編譯它。

警告

.NET 遠端處理預設不會執行驗證或加密。因此,建議在與用戶端或伺服器進行遠端互動之前,先採取所有必要步驟以驗證這些用戶端或伺服器的識別。因為 .NET 遠端處理應用程式需要 FullTrust 權限才能執行,所以如果將伺服器的存取權授與未授權用戶端,則該用戶端可如受到完全信任般地執行程式碼。請一律驗證您的端點並加密通訊資料流,方法是在網際網路資訊服務 (IIS) 中裝載遠端處理的型別,或建置自訂通道接收組,以完成這項作業。

編譯這個範例

  • 在命令提示字元中輸入下列命令:

    vbc /t:library RemoteType.vb

    csc /r:RemoteType.dll server.cs

    vbc /r:RemoteType.dll CAOClientVB.vb

CAOClient 檔案

//CAOClient.cs
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;

public class Client{

   public static void Main(string[] Args){
   
        // Loads the configuration file.
        RemotingConfiguration.Configure("CAOclient.exe.config");   
       
        ClientActivatedType CAObject = new ClientActivatedType();

        ILease serverLease = (ILease)RemotingServices.GetLifetimeService(CAObject);
        MyClientSponsor sponsor = new MyClientSponsor();

        // Note: If you do not pass an initial time, the first request will 
        // be taken from the LeaseTime settings specified in the 
        // server.exe.config file.
        serverLease.Register(sponsor);

        // Calls same method on each object.

        Console.WriteLine("Client-activated object: " + CAObject.RemoteMethod());

        Console.WriteLine("Press Enter to end the client application domain.");
        Console.ReadLine();
   }
}


public class MyClientSponsor : MarshalByRefObject, ISponsor{

    private DateTime lastRenewal;   

    public MyClientSponsor(){
        lastRenewal = DateTime.Now;
    }

    public TimeSpan Renewal(ILease lease){
    
        Console.WriteLine("I've been asked to renew the lease.");
        Console.WriteLine("Time since last renewal:" + (DateTime.Now - lastRenewal).ToString());

   lastRenewal = DateTime.Now;    
        return TimeSpan.FromSeconds(20);
    }
}
' CAOClientVB.vb
Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Lifetime

Public Class Client
   <MTAThread()> _
   Public Shared Sub Main()
   
      ' Loads the configuration file.
      RemotingConfiguration.Configure("CAOclient.exe.config")   
       
      Dim CAObject As ClientActivatedType = New ClientActivatedType()

      Dim ServerLease As ILease = CType(RemotingServices.GetLifetimeService(CAObject), ILease)
      Dim sponsor As MyClientSponsor = New MyClientSponsor()

      ' Note: If you do not pass an initial time, the first request will be taken from 
      ' the LeaseTime settings specified in the server.exe.config file.
      ServerLease.Register(sponsor)
      
      ' Calls same method on each object.

      Console.WriteLine("Client-activated object: " & CAObject.RemoteMethod())

      Console.WriteLine("Press Enter to end the client application domain.")
      Console.ReadLine()

   End Sub 'Main
End Class 'Client


Public Class MyClientSponsor 
   Inherits MarshalByRefObject
   Implements ISponsor

   Private LastRenewal As DateTime

   Public Sub New()
      LastRenewal = DateTime.Now
   End Sub   ' MyClientSponsor

   Public Function Renewal(ByVal lease As ILease) As TimeSpan Implements ISponsor.Renewal
    
      Console.WriteLine("I've been asked to renew the lease.")
      Dim Latest As DateTime = DateTime.Now
      Console.WriteLine("Time since last renewal: " & (Latest.Subtract(LastRenewal)).ToString())
      LastRenewal = Latest
      Return TimeSpan.FromSeconds(20)

   End Function 'Renewal

End Class 'MyClientSponsor

RemoteType 檔案

'RemoteType.vb
Imports System
Imports System.Runtime.Remoting.Lifetime
Imports System.Security.Principal

Public class ClientActivatedType
   Inherits MarshalByRefObject

   Public Function RemoteMethod() As String
      ' Announces to the server that the method has been called.
      Console.WriteLine("ClientActivatedType.RemoteMethod called.")

      ' Reports the client identity name.
      Return "RemoteMethod called. " & WindowsIdentity.GetCurrent().Name
   End Function  'RemoteMethod

   ' Overrides the lease settings for this object.
   Public Overrides Function InitializeLifetimeService() As Object

      Dim lease As ILease = CType(MyBase.InitializeLifetimeService(), ILease)
      
      If lease.CurrentState = LeaseState.Initial Then
         ' Normally, the initial lease time would be much longer.
         ' It is shortened here for demonstration purposes.
         lease.InitialLeaseTime = TimeSpan.FromSeconds(3)
         lease.SponsorshipTimeout = TimeSpan.FromSeconds(10)
         lease.RenewOnCallTime = TimeSpan.FromSeconds(2)
      End If

      Return lease
   End Function  'InitializeLifetimeService

End Class   'ClientActivatedType
// RemoteType.cs
using System;
using System.Runtime.Remoting.Lifetime;
using System.Security.Principal;

public class ClientActivatedType : MarshalByRefObject{


    // Overrides the lease settings for this object.
    public override Object InitializeLifetimeService(){

        ILease lease = (ILease)base.InitializeLifetimeService();
         // Normally, the initial lease time would be much longer.
         // It is shortened here for demonstration purposes.
        if (lease.CurrentState == LeaseState.Initial){
            lease.InitialLeaseTime = TimeSpan.FromSeconds(3);
            lease.SponsorshipTimeout = TimeSpan.FromSeconds(10);
            lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
        }
        return lease;
    }

    public string RemoteMethod(){

        // Announces to the server that the method has been called.
        Console.WriteLine("ClientActivatedType.RemoteMethod called.");

        // Reports the client identity name.
        return "RemoteMethod called. " + WindowsIdentity.GetCurrent().Name;

    }
}

Server.cs

using System;
using System.Runtime.Remoting;


public class Server{

   public static void Main(string[] Args){
   
      // Loads the configuration file.
        RemotingConfiguration.Configure("server.exe.config");
      
      Console.WriteLine("The server is listening. Press Enter to exit....");
      Console.ReadLine();   

        Console.WriteLine("Recycling memory...");
        GC.Collect();
        GC.WaitForPendingFinalizers();

   }
}

Server.exe.config

<configuration>
   <system.runtime.remoting>
      <application>
         <service>
            <activated type="ClientActivatedType, RemoteType"/>
         </service>
         <channels>
            <channel port="8080" ref="http"/>
         </channels>
      </application>
   </system.runtime.remoting>
</configuration>

CAOclient.exe.config

<configuration>
   <system.runtime.remoting>
      <application>
         <client url="http://localhost:8080">
            <activated type="ClientActivatedType, RemoteType"/>
         </client>
         <channels>
            <channel ref="http" port="0">
               <serverProviders>            
                  <formatter ref="soap" typeFilterLevel="Full"/>
                  <formatter ref="binary" typeFilterLevel="Full"/>
               </serverProviders>
            </channel>
         </channels>      </application>
   </system.runtime.remoting>
</configuration>

請參閱

其他資源

遠端處理範例
物件啟動和存留期