リモート処理の例 : 有効期間

有効期間リースのいくつかのシナリオを次のコード例で示します。CAOClient.exe は、最初の有効期間リースが経過した後、リモート型で指定されているのとは異なる時点で有効期間リースを更新するスポンサーを登録します。MyClientSponsor は、MarshalByRefObject を、リモートのリース マネージャに参照渡しされるように拡張します。この拡張を行わず、その代わりに SerializableAttribute 属性で装飾した場合、スポンサーは値渡しされ、サーバー アプリケーション ドメインで通常どおり実行されます。

このアプリケーションは、1 台のコンピュータ上で、またはネットワーク経由で実行されます。このアプリケーションをネットワーク経由で実行するには、クライアント構成の "localhost" をリモート コンピュータの名前で置き換える必要があります。

このサンプルでは、Visual Basic で書かれたコードと C# で書かれたコードの両方が使用されています。RemoteType.csCAOClient.cs もありますが、示されているコマンド ラインではコンパイルしていません。

ヒント

.NET リモート処理では、既定では認証または暗号化を行いません。したがって、クライアントやサーバーとリモートで対話する前に、それらの ID の確認に必要な手順をすべて実行することをお勧めします。.NET リモート処理アプリケーションの実行には、FullTrust アクセス許可が必要です。そのため、承認されていないクライアントがサーバー上でのアクセスを許可された場合は、完全な信頼を与えられているものとして、コードを実行できてしまいます。インターネット インフォメーション サービス (IIS : Internet Information Services) でリモート型をホストするか、リモート型をホストするためのカスタム チャネル シンク ペアを構築することによって、常にエンドポイントを認証し、通信ストリームを暗号化してください。

このサンプルをコンパイルするには

  • コマンド プロンプトで次のコマンドを入力します。

    vbc -t:library remote.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="https://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>

参照

その他の技術情報

リモート処理の例
オブジェクトのアクティベーションと有効期間