クライアントのチャネル レベルのプログラミング

ここでは、System.ServiceModel.ClientBase<TChannel> クラスとこれに関連するオブジェクト モデルを使用せずに、Windows Communication Foundation (WCF) クライアント アプリケーションを作成する方法を説明します。

sending messages

メッセージを送信し、応答を受信して処理できるようにするには、次の手順に従う必要があります。

  1. バインディングを作成します。

  2. チャネル ファクトリをビルドします。

  3. チャネルを作成します。

  4. 要求を送信し、応答を読み取ります。

  5. すべてのチャネル オブジェクトを閉じます。

バインディングの作成

受信側のケースと似ています (「サービス チャネル レベルのプログラミング」を参照)。バインディングを作成することでメッセージ送信が開始します。 この例では、新しい System.ServiceModel.Channels.CustomBinding を作成し、その要素コレクションに System.ServiceModel.Channels.HttpTransportBindingElement を追加します。

ChannelFactory のビルド

System.ServiceModel.Channels.IChannelListener を作成する代わりに、今回はバインディングで型パラメーターを System.ServiceModel.ChannelFactory<TChannel> にして ChannelFactory.CreateFactory を呼び出すことで、System.ServiceModel.Channels.IRequestChannel を作成します。 チャネル リスナーは受信メッセージを待機する側で使用されますが、チャネル ファクトリはチャネルを作成するために通信を開始する側で使用されます。 チャネル リスナーと同様に、チャネル ファクトリも使用する前に開く必要があります。

チャネルの作成

次に ChannelFactory<TChannel>.CreateChannel を呼び出して、IRequestChannel を作成します。 この呼び出しには、新しく作成するチャネルを使用して通信を行う対象となるエンドポイントのアドレスを使用します。 チャネルを作成したら、このチャネルで Open を呼び出して通信できる状態にします。 この Open の呼び出しにより、トランスポートの性質に応じて、目的のエンドポイントとの接続が開始されることもあれば、ネットワーク上では何も起こらないこともあります。

要求の送信と応答の読み取り

チャネルが開かれると、メッセージを作成して、チャネルの Request メソッドを使用して要求を送信し、応答が返ってくるのを待機できます。 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: {0}",
                              replymessage.Headers.Action);
        string data = replymessage.GetBody<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();
    }
    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