Esempio di configurazione remota: durata
Nell'esempio riportato di seguito vengono illustrati diversi scenari di lease di durata. CAOClient.exe
consente di registrare uno sponsor da cui, dopo il tempo di lease iniziale, viene rinnovato il lease in un momento diverso da quello specificato nel tipo remoto. MyClientSponsor
estende MarshalByRefObject per essere passato per riferimento al gestore di lease remoto; in caso contrario, e se invece fosse decorato con l'attributo SerializableAttribute, lo sponsor verrebbe passato per valore ed eseguito normalmente, ma nel dominio applicazione server.
Questa applicazione viene eseguita su un singolo computer o in una rete. Per eseguire l'applicazione in una rete, nella configurazione del client è necessario sostituire hostlocale con il nome del computer remoto.
Nell'esempio in questione viene utilizzato codice scritto sia in Visual Basic che in C#. RemoteType.cs
e CAOClient.cs
sono forniti a scopo di documentazione, ma non vengono compilati mediante le righe di comando specificate.
Attenzione .NET Remoting non consente di effettuare l'autenticazione né la crittografia per impostazione predefinita. Si consiglia dunque di eseguire tutte le azioni necessarie per verificare l'identità dei client o dei server prima di interagire con essi in modalità remota. Poiché l'esecuzione delle applicazioni .NET Remoting richiede autorizzazioni FullTrust, qualora a un client non autorizzato venisse concesso l'accesso al server, il client potrebbe eseguire codice come se fosse completamente attendibile. È necessario autenticare sempre gli endpoint e crittografare i flussi di comunicazione mediante l'hosting dei tipi remoti in Internet Information Services (IIS) oppure generando a questo scopo una coppia di sink di canale personalizzata.
Per compilare l'esempio
Digitare i seguenti comandi al prompt dei comandi:
vbc /t:library RemoteType.vb
csc /r:RemoteType.dll server.cs
vbc /r:RemoteType.dll CAOClientVB.vb
File 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
File 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>
Vedere anche
Esempi di comunicazione remota | Attivazione e durata degli oggetti