원격 서비스 예: 수명
다음 코드 예에서는 몇 가지 수명 임대 시나리오를 보여 줍니다. CAOClient.exe
는 초기 임대 기간 후 원격 형식에서 지정된 시기와 다른 시기에 임대를 갱신하는 스폰서를 등록합니다. MyClientSponsor
는 원격 임대 관리자에게 참조로 전달되도록 MarshalByRefObject를 확장합니다. 그렇지 않고 SerializableAttribute 특성으로 데코레이트되어 있으면 해당 스폰서는 값으로 전달되고 정상적으로 실행되지만 서버 응용 프로그램 도메인에서는 정상적으로 실행되지 않습니다.
이 응용 프로그램은 한 컴퓨터나 네트워크에서 실행됩니다. 이 응용 프로그램을 네트워크에서 실행하려면 클라이언트 구성의 **"localhost"**를 원격 컴퓨터의 이름으로 바꿔야 합니다.
이 샘플에서는 Visual Basic 및 C#으로 작성된 코드를 사용합니다. RemoteType.cs
및 CAOClient.cs
가 제공되지만 주어진 명령줄로 컴파일되지 않습니다.
경고
.NET Remoting에서는 기본적으로 인증이나 암호화 작업을 수행하지 않습니다. 따라서 원격으로 클라이언트나 서버와 상호 작용하기 전에 클라이언트나 서버의 ID를 확인하는 데 필요한 모든 단계를 수행하는 것이 좋습니다. .NET Remoting 응용 프로그램을 실행하려면 FullTrust 권한이 필요하므로 권한이 없는 클라이언트가 서버에 액세스할 수 있게 되면 해당 클라이언트는 완전히 신뢰받는 것처럼 코드를 실행할 수 있습니다. IIS(인터넷 정보 서비스)에서 원격화된 형식을 호스팅하거나 사용자 지정 채널 싱크 쌍을 만들어서 항상 끝점을 인증하고 통신 스트림을 암호화하십시오.
이 샘플을 컴파일하려면
명령 프롬프트에서 다음 명령을 입력합니다.
vbc /t:library RemoteType.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>