次の方法で共有


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

有効期間リースのいくつかのシナリオを次のコード例で示します。Client.exe は、最初の有効期間リースが経過した後、ClientActivatedType.InitializeLifetimeService() での指定とは異なる TimeSpan で有効期間リースを更新するスポンサを登録します。MyClientSponsorMarshalByRefObject を、Server.exe アプリケーション ドメイン内で、リース マネージャに参照によって渡されるように拡張します。このアプリケーションは、1 台のコンピュータ上、またはネットワーク経由で実行されます。このアプリケーションをネットワーク上で実行する場合は、クライアント構成の "localhost" をリモート コンピュータの名前に置き換える必要があります。

Caution note注意 :

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

Server.exe を実行し、次に Client.exe を実行すると、次のような出力が表示されます。

Server.exe:

C:\projects\Lifetime\Server\bin>server

The server is listening. Press Enter to exit....

ClientActivatedType.RemoteMethod called.

Client.exe:

C:\projects\Lifetime\Client\bin>client

Client-activated object: RemoteMethod called. MyDomain\SomeUser

Press Enter to end the client application domain.

I've been asked to renew the lease.

Time since last renewal:00:00:09.9432506

I've been asked to renew the lease.

Time since last renewal:00:00:29.9237760

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

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

    [C#]

    csc /t:library RemoteType.cs
    csc /r:System.Runtime.Remoting.dll /r:RemoteType.dll server.cs
    csc /r:System.Runtime.Remoting.dll /r:RemoteType.dll client.cs
    

[Visual Basic]

RemoteType

[C#]

using System;
using System.Runtime.Remoting.Lifetime;
using System.Security.Principal;

namespace RemoteType
{
    public class ClientActivatedType : MarshalByRefObject
    {
        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;
        }
    }
}

[Visual Basic]

Imports System
Imports System.Runtime.Remoting.Lifetime
Imports System.Security.Principal

Namespace RemoteType
Public Class ClientActivatedType
    Inherits MarshalByRefObject

    Public Overrides Function InitializeLifetimeService() As Object
        Dim lease As ILease = MyBase.InitializeLifetimeService()

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

    Public Function RemoteMethod() As String
        Console.WriteLine("ClientActivatedType.RemoteMethod called.")

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

End Class
End Namespace

サーバー

using System;
using System.Runtime.Remoting;

namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            RemotingConfiguration.Configure("Server.exe.config", false);
            Console.WriteLine("The server is listening. Press Enter to exit....");
            Console.ReadLine();
        }
    }
}
Imports System
Imports System.Runtime.Remoting

Class Program
    Shared Sub Main()
        RemotingConfiguration.Configure("Server.exe.config", False)
        Console.WriteLine("The server is listening. Press Enter to exit....")
        Console.ReadLine()
    End Sub
End Class

Server.exe.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
    <application>
      <channels>
        <channel ref="tcp" port="1234">
          <serverProviders>
            <formatter ref="binary" typeFilterLevel="Full"/>
          </serverProviders>
          <clientProviders>
            <formatter ref="binary"/>
          </clientProviders>
        </channel>
      </channels>
      <service>
        <activated type="RemoteType.ClientActivatedType, RemoteType" />
      </service>
    </application>
  </system.runtime.remoting>
</configuration>

クライアント

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;
using RemoteType;

class Client
{
    static void Main(string[] args)
    {
        RemotingConfiguration.Configure("Client.exe.config",false);
        ClientActivatedType obj = new ClientActivatedType();

        ILease lease = (ILease)obj.GetLifetimeService();
        MyClientSponsor sponsor = new MyClientSponsor();
        lease.Register(sponsor);

        Console.WriteLine("Client-activated object: " + obj.RemoteMethod());
        Console.WriteLine("Press Enter to end the client application domain.");
        Console.ReadLine();
    }
}

public class MyClientSponsor : MarshalByRefObject, ISponsor
{
    private DateTime lastRenewal;

    public MyClientSponsor()
    {
        Console.WriteLine("MyClientSponsor.ctor called");
        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);
    }
}
Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Lifetime
Imports RemoteType

Class Client

    Shared Sub Main()
        RemotingConfiguration.Configure("Client.exe.config", False)
        Dim obj As ClientActivatedType = New ClientActivatedType()

        Dim lease As ILease = CType(obj.GetLifetimeService(), ILease)
        Dim sponsor As MyClientSponsor = New MyClientSponsor()
        lease.Register(sponsor)

        Console.WriteLine("Client-activated object: " + obj.RemoteMethod())
        Console.WriteLine("Press Enter to end the client application domain.")
        Console.ReadLine()
    End Sub

End Class

Public Class MyClientSponsor
    Inherits MarshalByRefObject
    Implements ISponsor

    Dim lastRenewal As DateTime

    Public Sub New()
        lastRenewal = DateTime.Now
    End Sub

    Public Function Renewal(ByVal lease As System.Runtime.Remoting.Lifetime.ILease) As System.TimeSpan Implements System.Runtime.Remoting.Lifetime.ISponsor.Renewal
        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)
    End Function
End Class

Client.exe.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
    <application>
      <channels>
        <channel ref="tcp" port="0">
          <clientProviders>
            <formatter ref="binary"/>
          </clientProviders>
          <serverProviders>
            <formatter ref="binary" typeFilterLevel="Full"/>
          </serverProviders>
        </channel>
      </channels>
      <client url="tcp://localhost:1234">
        <activated type="RemoteType.ClientActivatedType, RemoteType" />
      </client>
    </application>
  </system.runtime.remoting>
</configuration>

関連項目

その他の技術情報

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

Footer image

Copyright © 2007 by Microsoft Corporation.All rights reserved.