다음을 통해 공유


클라이언트 Channel-Level 프로그래밍

이 항목에서는 클래스 및 관련 개체 모델을 사용하지 않고 WCF(Windows Communication Foundation) 클라이언트 애플리케이션을 System.ServiceModel.ClientBase<TChannel> 작성하는 방법에 대해 설명합니다.

메시지 보내기

메시지를 보내고 회신을 받고 처리할 준비가 되려면 다음 단계가 필요합니다.

  1. 바인딩을 만듭니다.

  2. 채널 팩터리를 빌드합니다.

  3. 채널을 만듭니다.

  4. 요청을 보내고 회신을 읽습니다.

  5. 모든 채널 개체를 닫습니다.

바인딩 만들기

수신 사례와 유사하게( 서비스 Channel-Level 프로그래밍 참조) 바인딩을 만들어 메시지 보내기가 시작됩니다. 다음은 새 System.ServiceModel.Channels.CustomBinding 항목을 만들고 Elements 컬렉션에 System.ServiceModel.Channels.HttpTransportBindingElement 추가하는 예제입니다.

채널 팩토리 빌드하기

이번에는 System.ServiceModel.Channels.IChannelListener를 생성하는 대신에, 형식 매개 변수가 System.ServiceModel.ChannelFactory<TChannel>인 바인딩에서 ChannelFactory.CreateFactory를 호출하여 System.ServiceModel.Channels.IRequestChannel을 생성합니다. 채널 수신기는 들어오는 메시지를 기다리는 쪽에서 사용되지만 채널 팩터리에서 통신을 시작하여 채널을 만드는 데 사용됩니다. 채널 수신기와 마찬가지로 채널 팩터리를 먼저 열어야 사용할 수 있습니다.

채널 만들기

그런 다음 ChannelFactory<TChannel>.CreateChannel을 호출하여 IRequestChannel을 만듭니다. 이 호출은 생성되는 새 채널을 사용하여 통신하려는 엔드포인트의 주소를 사용합니다. 채널이 있으면 Open on을 호출하여 통신 준비가 된 상태로 전환합니다. 전송의 특성에 따라 이 Open 호출은 대상 엔드포인트와의 연결을 시작하거나 네트워크에서 아무 작업도 수행하지 않을 수 있습니다.

요청 보내기 및 회신 읽기

채널이 열리면 메시지를 만들고 채널의 Request 메서드를 사용하여 요청을 보내고 회신이 돌아올 때까지 기다릴 수 있습니다. 이 메서드가 반환되면 엔드포인트의 회신이 무엇인지 확인하기 위해 읽을 수 있는 회신 메시지가 있습니다.

개체 닫기

리소스 누출을 방지하기 위해 더 이상 필요하지 않은 경우 통신에 사용되는 개체를 닫습니다.

다음 코드 예제에서는 채널 팩터리를 사용하여 메시지를 보내고 회신을 읽는 기본 클라이언트를 보여 줍니다.

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
namespace ProgrammingChannels
{
class Client
{

    static void RunClient()
    {
        //Step1: Create a binding with just HTTP.
        BindingElement[] bindingElements = new BindingElement[2];
        bindingElements[0] = new TextMessageEncodingBindingElement();
        bindingElements[1] = new HttpTransportBindingElement();
        CustomBinding binding = new CustomBinding(bindingElements);

        //Step2: Use the binding to build the channel factory.
        IChannelFactory<IRequestChannel> factory =
        binding.BuildChannelFactory<IRequestChannel>(
                         new BindingParameterCollection());
        //Open the channel factory.
        factory.Open();

        //Step3: Use the channel factory to create a channel.
        IRequestChannel channel = factory.CreateChannel(
           new EndpointAddress("http://localhost:8080/channelapp"));
        channel.Open();

        //Step4: Create a message.
        Message requestmessage = Message.CreateMessage(
            binding.MessageVersion,
            "http://contoso.com/someaction",
             "This is the body data");
        //Send message.
        Message replymessage = channel.Request(requestmessage);
        Console.WriteLine("Reply message received");
        Console.WriteLine($"Reply action: {replymessage.Headers.Action}");
        string data = replymessage.GetBody<string>();
        Console.WriteLine($"Reply content: {data}");

        //Step5: Do not forget to close the message.
        replymessage.Close();
        //Do not forget to close the channel.
        channel.Close();
        //Do not forget to close the factory.
        factory.Close();
    }
    public static void Main()
    {
        Console.WriteLine("Press [ENTER] when service is ready");
        Console.ReadLine();
        RunClient();
        Console.WriteLine("Press [ENTER] to exit");
        Console.ReadLine();
    }
}
}

Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports System.ServiceModel.Configuration

Namespace ProgrammingChannels
    Friend Class Client

        Private Shared Sub RunClient()
            'Step1: Create a binding with just HTTP.
            Dim bindingElements(1) As BindingElement = {New TextMessageEncodingBindingElement(), _
                                                        New HttpTransportBindingElement()}
            Dim binding As New CustomBinding(bindingElements)

            'Step2: Use the binding to build the channel factory.
            Dim factory = binding.BuildChannelFactory(Of IRequestChannel)(New BindingParameterCollection())
            'Open the channel factory.
            factory.Open()

            'Step3: Use the channel factory to create a channel.
            Dim channel = factory.CreateChannel(New EndpointAddress("http://localhost:8080/channelapp"))
            channel.Open()

            'Step4: Create a message.
            Dim requestmessage = Message.CreateMessage(binding.MessageVersion, _
                                                       "http://contoso.com/someaction", _
                                                       "This is the body data")
            'Send message.
            Dim replymessage = channel.Request(requestmessage)
            Console.WriteLine("Reply message received")
            Console.WriteLine("Reply action: {0}", replymessage.Headers.Action)
            Dim data = replymessage.GetBody(Of String)()
            Console.WriteLine("Reply content: {0}", data)

            'Step5: Do not forget to close the message.
            replymessage.Close()
            'Do not forget to close the channel.
            channel.Close()
            'Do not forget to close the factory.
            factory.Close()
        End Sub

        Public Shared Sub Main()

            Console.WriteLine("Press [ENTER] when service is ready")
            Console.ReadLine()
            RunClient()
            Console.WriteLine("Press [ENTER] to exit")
            Console.ReadLine()

        End Sub
    End Class
End Namespace