다음을 통해 공유


원격 서비스 예제: CallContext

이 샘플은 CallContext 클래스와 ILogicalThreadAffinative 인터페이스를 사용하여 원격 클라이언트 응용 프로그램과 원격 서버 응용 프로그램 간에 데이터를 전달합니다.

이 응용 프로그램은 단일 컴퓨터에서 실행되거나 네트워크에서 실행됩니다. 네트워크를 통해 이 응용 프로그램을 실행하려면 클라이언트 구성의 "localhost"를 원격 컴퓨터의 이름으로 바꿉니다.

Caution note주의:

.NET Remoting은 기본적으로 인증이나 암호화를 수행하지 않습니다. 따라서 원격으로 클라이언트 또는 서버와 상호 작용하기 전에 해당 클라이언트 또는 서버의 ID를 확인하는 데 필요한 모든 단계를 수행하는 것이 좋습니다. .NET Remoting 응용 프로그램이 실행되려면 FullTrust 권한이 필요하기 때문에 인증되지 않은 클라이언트가 서버에 액세스할 수 있도록 허용된 경우에는 클라이언트가 완전히 신뢰된 것처럼 코드를 실행할 수 있습니다. 따라서 항상 클라이언트를 인증하고 통신 스트림을 암호화하십시오. 자세한 내용은 원격 서비스의 보안를 참조하십시오.

이 샘플을 컴파일하려면

  • 명령 프롬프트에 다음 명령을 입력합니다.

    [Visual Basic]

    vbc /r:System.Runtime.Remoting.dll /t:library MyRemoteType.vb
    vbc /r:System.Runtime.Remoting.dll /r:MyRemoteType.dll client.vb
    vbc /r:System.Runtime.Remoting.dll /r:MyRemoteType.dll server.vb
    

    [C#]

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

MyRemoteType

Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Messaging

Namespace [Shared]
    Public Class MyRemoteType
    Inherits MarshalByRefObject

    Private starttime As DateTime

    Public Sub New()
        Console.WriteLine("A MyRemoteObject instance has been created.")
        starttime = DateTime.Now
    End Sub

    Protected Overrides Sub Finalize()
        Console.WriteLine("MyRemoteObject being collected after " & (New TimeSpan(DateTime.Now.Ticks - starttime.Ticks)).ToString() & " seconds.")
    End Sub

    Public Function GetServerTime() As DateTime
        Console.WriteLine("Time requested by a client.")

        ' This call overwrites the client's CallContextString.
        CallContext.SetData("ServerThreadData", New CallContextString("This is the server side replacement."))
        Return DateTime.Now
    End Function
End Class

'  One method of communicating between client and server is 
'  to use the CallContext. Calling CallContext.SetData essentially puts the data
'  in a Thread Local Store. This means that the information is available 
'  to that thread or that "logical" thread (across application domains) only.
<Serializable()> _
Public Class CallContextString
    Implements ILogicalThreadAffinative

    Dim _str As String = ""

    Public Sub New(ByVal str As String)
        _str = str
        Console.WriteLine("CallContextString created.")
    End Sub

    Public Overrides Function ToString() As String
        Return _str
    End Function
End Class
End Namespace
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;

namespace Shared
{
    public class MyRemoteType : MarshalByRefObject 
    {
        private DateTime starttime;

        public MyRemoteType()
        {
            Console.WriteLine("A MyRemoteObject instance has been created.");
            starttime = DateTime.Now;
        }

        ~MyRemoteType()
        {
            Console.WriteLine("MyRemoteObject being collected after " + (new TimeSpan(DateTime.Now.Ticks - starttime.Ticks)).ToString() + " seconds.");
        }

        public DateTime GetServerTime()
        {
            Console.WriteLine("Time requested by a client.");

            // This call overwrites the client's CallContextString.
            CallContext.SetData("ServerThreadData", new CallContextString("This is the server side replacement."));
            return DateTime.Now;
        }
    }

    //  One method of communicating between client and server is 
    //  to use the CallContext. Calling CallContext.SetData essentially puts the data
    //  in a Thread Local Store. This means that the information is available 
    //  to that thread or that "logical" thread (across application domains) only.
    [Serializable]
    public class CallContextString : ILogicalThreadAffinative
    {
        String _str = "";

        public CallContextString(String str)
        {
            _str = str;
            Console.WriteLine("CallContextString created.");
        }

        public override String ToString()
        {
            return _str;
        }
    }
}

Client

[Visual Basic]

Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Http
Imports System.Runtime.Remoting.Contexts
Imports System.Runtime.Remoting.Messaging
Imports [Shared]

Public Class Client
    Public Shared Sub Main()
        ' Register Channel
        Dim channel As HttpChannel = New HttpChannel()
        ChannelServices.RegisterChannel(channel, False)

        ' Register MyRemoteObject
        RemotingConfiguration.RegisterWellKnownClientType( _
                GetType(MyRemoteType), _
                "https://localhost:8080/MyRemoteObject")

        ' Add a CallContextString object to the call context
        CallContext.SetData("ServerThreadData", New CallContextString("This is the thread data inserted on the client thread."))

        Console.WriteLine("CallContextString prior to the call: " & CallContext.GetData("ServerThreadData").ToString())
        Dim service As MyRemoteType = New MyRemoteType()
        Console.WriteLine("Server time is: " & service.GetServerTime().ToLongTimeString())
        Console.WriteLine("CallContextString after the call: " & CallContext.GetData("ServerThreadData").ToString())
    End Sub
End Class

[C#]

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
using Shared;

namespace Client
{
    public class Client
    {
        public static void Main(string[] args)
        {
            // Register Channel
            HttpChannel channel = new HttpChannel();
            ChannelServices.RegisterChannel(channel, false);

            // Register MyRemoteObject
            RemotingConfiguration.RegisterWellKnownClientType(
                typeof(MyRemoteType),
                "https://localhost:8080/MyRemoteObject");

            // Add a CallContextString object to the call context
            CallContext.SetData("ServerThreadData", new CallContextString("This is the thread data inserted on the client thread."));

            Console.WriteLine("CallContextString prior to the call: " + CallContext.GetData("ServerThreadData").ToString());
            MyRemoteType service = new MyRemoteType();
            Console.WriteLine("Server time is: " + service.GetServerTime().ToLongTimeString());
            Console.WriteLine("CallContextString after the call: " + CallContext.GetData("ServerThreadData").ToString());
        }
    }
}

Server

[Visual Basic]

Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Http
Imports [Shared]

Public Class Server

    Public Shared Sub Main()
        ' Register channel
        Dim channel As HttpChannel = New HttpChannel(8080)
        ChannelServices.RegisterChannel(channel, False)

        ' Register MyRemoteObject
        RemotingConfiguration.RegisterWellKnownServiceType( _
            GetType(MyRemoteType), _
            "MyRemoteObject", _
            WellKnownObjectMode.SingleCall)

        Console.WriteLine("Press enter to stop this process.")
        Console.ReadLine()
    End Sub

End Class

[C#]

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using Shared;

namespace Server
{
    class Server
    {
        static void Main(string[] args)
        {
            // Register channel
            HttpChannel channel = new HttpChannel(8080);
            ChannelServices.RegisterChannel(channel, false);

            // Register MyRemoteObject
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(MyRemoteType),
                "MyRemoteObject",
                WellKnownObjectMode.SingleCall);

            Console.WriteLine("Press enter to stop this process.");
            Console.ReadLine();
        }
    }
}

참고 항목

기타 리소스

원격 서비스 예제

Footer image

Copyright © 2007 by Microsoft Corporation. All rights reserved.