Exemplo do Sistema de Interação Remota: Vidas úteis
O seguinte exemplo de código demonstra vários da tempo de vida-arrendamento cenários. Client.exe registra um patrocinador que (após o tempo inicial arrendamento) renova o arrendamento para um TimeSpan diferentes de que especificou no ClientActivatedType.InitializeLifetimeService(). Esteja ciente que o MyClientSponsor estende MarshalByRefObject para que ele possa ser passado por referência para o gerente de concessão (o Server.exe de domínio de aplicativo). This aplicativo Runs on a single computador OR Na Horizontal a rede. Se você deseja executar este aplicativo através de uma rede, você deve substituir "localhost" na configuração do cliente com o nome do computador remoto.
Aviso
Sistema de interação remota .NET não executa a autenticação ou criptografia por padrão.Therefore, it is recommended that you Take All steps necessary to the identidade of Clients verificar or Servidores before interacting with them remotely.Because Applications Remoting .NET FullTrust Permissions to Require executar, IF a cliente Unauthorized were Granted acessar on your servidor, the cliente Could executar Código as though IT were totalmente confiável.Sempre Authenticate Your Endpoints and criptografar the streams Communication, Either by Hosting Your Types remoted in Serviços de Informações da Internet (IIS) or by compilação a personalizado par coletor de canal to this trabalho.
Servidor.Exe de execução e, em seguida, Client.exe Você deverá ver saída semelhante a seguinte:
Servidor.exe:
C:\projects\Lifetime\Server\bin>server
The server is listening. Press Enter to exit....
ClientActivatedType.RemoteMethod called.
Cliente.exe:
C:\projects\Lifetime\Client\bin>client
Client-activated object: RemoteMethod called. REDMOND\migree
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
Para compilar este exemplo
Type the seguinte Comandos at the prompt de comando:
[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
Server
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
Servidor. 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>
Cliente.
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
Cliente. 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>