How to:使用雙工合約存取服務

Windows Communication Foundation (WCF) 的一個功能,就是能夠建立使用雙工訊息模式的服務。 這個模式可讓服務透過回呼與用戶端通訊。 本主題說明在執行回呼介面的用戶端類別中建立 WCF 用戶端的步驟。

雙重繫結會向服務公開用戶端的 IP 位址, 用戶端應該利用安全性來確保它只與信任的服務連接。

如需建立基本 WCF 服務和用戶端的教學課程,請參閱 開始使用教學課程。

若要存取雙工服務

  1. 建立包含兩個介面的服務。 第一個介面主要供服務使用,第二個則是供回呼使用。 如需有關建立雙工服務的詳細資訊,請參閱 如何:建立雙工合約

  2. 執行服務。

  3. 使用 [ System.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

另請參閱