如何:使用双工协定访问服务

Windows Communication Foundation (WCF) 的一个功能是可以创建使用双工消息传递模式的服务。 此模式允许服务通过回调与客户端进行通信。 本主题演示在实现回调接口的客户端类中创建 WCF 客户端的步骤。

双向绑定向服务公开客户端的 IP 地址。 客户端应使用安全来确保仅连接到自己信任的服务。

有关创建基本 WCF 服务和客户端的教程,请参阅入门教程

访问双工服务

  1. 创建包含两个接口的服务。 第一个接口用于服务,第二个接口用于回调。 有关创建双工服务的详细信息,请参阅如何:创建双工协定

  2. 运行服务。

  3. 使用 ServiceModel 元数据实用工具 (Svcutil.exe) 为客户端生成协定(接口)。 有关如何执行此操作的信息,请参阅如何:创建客户端

  4. 在客户端类中实现回调接口,如下面的示例所示。

    public class CallbackHandler : ICalculatorDuplexCallback
    {
        public void Result(double result)
        {
            Console.WriteLine("Result ({0})", result);
        }
        public void Equation(string equation)
        {
            Console.WriteLine("Equation({0})", equation);
        }
    }
    
    Public Class CallbackHandler
    Implements ICalculatorDuplexCallback
       Public Sub Result (ByVal result As Double)
          Console.WriteLine("Result ({0})", result)
       End Sub
        Public Sub Equation(ByVal equation As String)
            Console.WriteLine("Equation({0})", equation)
        End Sub
    End Class
    
  5. 创建的 InstanceContext 类的实例。 构造函数需要客户端类的一个实例。

    InstanceContext site = new InstanceContext(new CallbackHandler());
    
    Dim site As InstanceContext = New InstanceContext(new CallbackHandler())
    
  6. 使用需要 InstanceContext 对象的构造函数创建 WCF 客户端的一个实例。 该构造函数的第二个参数是配置文件中找到的终结点的名称。

    CalculatorDuplexClient wcfClient = new CalculatorDuplexClient(site, "default");
    
    Dim wcfClient As New CalculatorDuplexClient(site, "default")
    
  7. 根据需要调用 WCF 客户端的方法。

示例

下面的代码示例演示如何创建一个访问双工协定的客户端类。

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

// Define class that implements the callback interface of duplex
// contract.
public class CallbackHandler : ICalculatorDuplexCallback
{
  public void Result(double result)
  {
    Console.WriteLine("Result({0})", result);
  }
  public void Equation(string equation)
  {
    Console.WriteLine("Equation({0})", equation);
  }
}

public class Client
{
  public static void Main()
  {
    // Picks up configuration from the config file.

    CalculatorDuplexClient wcfClient
      = new CalculatorDuplexClient(new InstanceContext(new CallbackHandler()));
    try
    {
      // Call the AddTo service operation.
      double value = 100.00D;
      wcfClient.AddTo(value);

      // Call the SubtractFrom service operation.
      value = 50.00D;
      wcfClient.SubtractFrom(value);

      // Call the MultiplyBy service operation.
      value = 17.65D;
      wcfClient.MultiplyBy(value);

      // Call the DivideBy service operation.
      value = 2.00D;
      wcfClient.DivideBy(value);

      // Complete equation.
      wcfClient.Clear();

      // Wait for callback messages to complete before
      // closing.
      System.Threading.Thread.Sleep(5000);

      // Close the WCF client.
      wcfClient.Close();
      Console.WriteLine("Done!");
    }
    catch (TimeoutException timeProblem)
    {
      Console.WriteLine("The service operation timed out. " + timeProblem.Message);
      wcfClient.Abort();
      Console.Read();
    }
    catch (CommunicationException commProblem)
    {
      Console.WriteLine("There was a communication problem. " + commProblem.Message);
      wcfClient.Abort();
      Console.Read();
    }
  }
}
Imports System.ServiceModel

Namespace Microsoft.ServiceModel.Samples

    ' The service contract is defined in generatedClient.vb, generated from the service by the svcutil tool.

    ' Define class which implements callback interface of duplex contract
    Public Class CallbackHandler
        Implements ICalculatorDuplexCallback

        Public Sub Result(ByVal result As Double) Implements ICalculatorDuplexCallback.Result
            Console.WriteLine("Result({0})", result)
        End Sub

        Public Sub Equation(ByVal eqn As String) Implements ICalculatorDuplexCallback.Equation
            Console.WriteLine("Equation({0})", eqn)
        End Sub
    End Class

    Class Client
        Public Shared Sub Main()

            ' Construct InstanceContext to handle messages on callback interface
            Dim instanceContext As New InstanceContext(New CallbackHandler())

            ' Create a client
            Dim wcfClient As New CalculatorDuplexClient(instanceContext)
            Console.WriteLine("Press <ENTER> to terminate client once the output is displayed.")
            Console.WriteLine()

            Try
                ' Call the AddTo service operation.
                Dim value As Double = 100
                wcfClient.AddTo(value)

                ' Call the SubtractFrom service operation.
                value = 50
                wcfClient.SubtractFrom(value)

                ' Call the MultiplyBy service operation.
                value = 17.65
                wcfClient.MultiplyBy(value)

                ' Call the DivideBy service operation.
                value = 2
                wcfClient.DivideBy(value)

                ' Complete equation
                wcfClient.Clear()

                Console.ReadLine()

                'Closing the client gracefully closes the connection and cleans up resources
                wcfClient.Close()

            Catch timeout As TimeoutException
                Console.WriteLine(timeout.Message)
                wcfClient.Abort()
            Catch commException As CommunicationException
                Console.WriteLine(commException.Message)
                wcfClient.Abort()
            End Try
        End Sub

    End Class

End Namespace

另请参阅