次の方法で共有


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

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

メッセージの送信

メッセージを送信し、応答を受信して処理する準備を整えるためには、次の手順が必要です。

  1. バインドを作成します。

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

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

  4. 要求を送信し、応答を読み取る。

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

バインディングの作成

受信ケースと同様に (Service Channel-Level プログラミングを参照)、メッセージの送信はバインディングの作成から始まります。 次の使用例は、新しい System.ServiceModel.Channels.CustomBinding を作成し、その Elements コレクションに 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 メソッドを使用して要求を送信し、応答が返されるのを待つことができます。 このメソッドが返されると、エンドポイントの応答が何であったかを確認するために読み取ることができる応答メッセージが表示されます。

オブジェクトを閉じる

リソースのリークを回避するために、不要になった通信で使用されるオブジェクトを閉じます。

次のコード例は、チャネル ファクトリを使用してメッセージを送信し、応答を読み取る基本的なクライアントを示しています。

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