Freigeben über


Remotingbeispiel: Lebensdauer

Mit dem folgenden Codebeispiel werden einige der Szenarios für Lebensdauerleases veranschaulicht. CAOClient.exe registriert einen Sponsor, der (nach Ablauf der ersten Leasedauer) den Lease zu einem anderen Zeitpunkt als dem im Remotetyp angegebenen erneuert. Beachten Sie, dass MarshalByRefObject von MyClientSponsor für die Übergabe anhand eines Verweises an den Remotelease-Manager erweitert wird. Würde stattdessen eine Erweiterung um das SerializableAttribute-Attribut erfolgen, würde der Sponsor anhand eines Werts übergeben und normal ausgeführt werden, jedoch in der Serveranwendungsdomäne.

Diese Anwendung wird auf einem einzelnen Computer oder über ein Netzwerk ausgeführt. Wenn Sie die Anwendung über ein Netzwerk ausführen möchten, müssen Sie "localhost" in der Clientkonfiguration durch den Namen des Remotecomputers ersetzen.

In diesem Beispiel wird Code in Visual Basic und in C# aufgeführt. RemoteType.cs und CAOClient.cs stehen zur Verfügung, werden jedoch nicht durch die angegebenen Befehlszeilen kompiliert.

Warnung

.NET Remoting führt standardmäßig keine Authentifizierung oder Verschlüsselung aus. Daher empfiehlt es sich, alle erforderlichen Schritte auszuführen, um die Identität von Clients und Servern vor der Remoteinteraktion eindeutig zu überprüfen. Da für die Ausführung von .NET Remoting-Anwendungen die Berechtigung FullTrust erforderlich ist, könnte ein nicht autorisierter Client, dem der Zugriff auf den Server gewährt wurde, Code so ausführen, als ob er vollständig vertrauenswürdig wäre. Authentifizieren Sie stets die Endpunkte, und verschlüsseln Sie die Kommunikationsstreams, entweder durch Hosten der Remotetypen in Internetinformationsdienste (Internet Information Services, IIS), oder indem Sie für diese Aufgabe ein benutzerdefiniertes Channelempfängerpaar erstellen.

So kompilieren Sie dieses Beispiel

  • Geben Sie an der Eingabeaufforderung die folgenden Befehle ein:

    vbc /t:library RemoteType.vb

    csc /r:RemoteType.dll server.cs

    vbc /r:RemoteType.dll CAOClientVB.vb

Datei "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

Datei "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>

Siehe auch

Weitere Ressourcen

Remotingbeispiele
Aktivierung und Lebensdauer von Objekten