Delen via


How to: Use a Windows Communication Foundation Client

This is the last of six tasks required to create a basic Windows Communication Foundation (WCF) service and a client that can call the service. For an overview of all six of the tasks, see the Getting Started Tutorial topic.

Once a Windows Communication Foundation (WCF) proxy has been created and configured, a client instance can be created and the client application can be compiled and used to communicate with the WCF service. This topic describes procedures for creating and using a WCF client. This procedure does three things:

  1. Creates a WCF client.

  2. Calls the service operations from the generated proxy.

  3. Closes the client once the operation call is completed.

The code discussed in the procedure is also provided in the example following the procedure. The code in this task should be placed in the Main() method of the generated Program class in the client project.

To use a Windows Communication Foundation client

  1. Create an EndpointAddress instance for the base address of the service you are going to call and then create an WCF Client object.

    ' Step 1: Create an endpoint address and an instance of the WCF Client.
    Dim epAddress As New EndpointAddress("https://localhost:8000/ServiceModelSamples/Service/CalculatorService")
    Dim Client As New CalculatorClient(New WSHttpBinding(), epAddress)
    
    //Step 1: Create an endpoint address and an instance of the WCF Client.
    CalculatorClient client = new CalculatorClient();
    
  2. Call the client operations from within the Client.

    'Step 2: Call the service operations.
    'Call the Add service operation.
    Dim value1 As Double = 100D
    Dim value2 As Double = 15.99D
    Dim result As Double = Client.Add(value1, value2)
    Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result)
    
    'Call the Subtract service operation.
    value1 = 145D
    value2 = 76.54D
    result = Client.Subtract(value1, value2)
    Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result)
    
    'Call the Multiply service operation.
    value1 = 9D
    value2 = 81.25D
    result = Client.Multiply(value1, value2)
    Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result)
    
    'Call the Divide service operation.
    value1 = 22D
    value2 = 7D
    result = Client.Divide(value1, value2)
    Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result)
    Shared Sub Main()
        ' Step 1 of the address configuration procedure: Create a URI to serve as the base address.
        Dim baseAddress As New Uri("https://localhost:8000/ServiceModelSamples/Service")
    
        ' Step 2 of the hosting procedure: Create ServiceHost
        Dim selfHost As New ServiceHost(GetType(CalculatorService), baseAddress)
        Try
    
            ' Step 3 of the hosting procedure: Add a service endpoint.
            ' Add a service endpoint
            selfHost.AddServiceEndpoint( _
                GetType(ICalculator), _
                New WSHttpBinding(), _
                "CalculatorService")
    
            ' Step 4 of the hosting procedure: Enable metadata exchange.
            ' Enable metadata exchange
            Dim smb As New ServiceMetadataBehavior()
            smb.HttpGetEnabled = True
            selfHost.Description.Behaviors.Add(smb)
    
            ' Step 5 of the hosting procedure: Start (and then stop) the service.
            selfHost.Open()
            Console.WriteLine("The service is ready.")
            Console.WriteLine("Press <ENTER> to terminate service.")
            Console.WriteLine()
            Console.ReadLine()
    
            ' Close the ServiceHostBase to shutdown the service.
            selfHost.Close()
        Catch ce As CommunicationException
            Console.WriteLine("An exception occurred: {0}", ce.Message)
            selfHost.Abort()
        End Try
    End Sub
    
    // Step 2: Call the service operations.
    // Call the Add service operation.
    double value1 = 100.00D;
    double value2 = 15.99D;
    double result = client.Add(value1, value2);
    Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);
    
    // Call the Subtract service operation.
    value1 = 145.00D;
    value2 = 76.54D;
    result = client.Subtract(value1, value2);
    Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);
    
    // Call the Multiply service operation.
    value1 = 9.00D;
    value2 = 81.25D;
    result = client.Multiply(value1, value2);
    Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);
    
    // Call the Divide service operation.
    value1 = 22.00D;
    value2 = 7.00D;
    result = client.Divide(value1, value2);
    Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);
    
    static void Main(string[] args)
    {
    
        // Step 1 of the address configuration procedure: Create a URI to serve as the base address.
        Uri baseAddress = new Uri("https://localhost:8000/ServiceModelSamples/Service");
    
        // Step 2 of the hosting procedure: Create ServiceHost
        ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
    
        try
        {
    
    
            // Step 3 of the hosting procedure: Add a service endpoint.
            selfHost.AddServiceEndpoint(
                typeof(ICalculator),
                new WSHttpBinding(),
                "CalculatorService");
    
    
            // Step 4 of the hosting procedure: Enable metadata exchange.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            selfHost.Description.Behaviors.Add(smb);
    
            // Step 5 of the hosting procedure: Start (and then stop) the service.
            selfHost.Open();
            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();
    
            // Close the ServiceHostBase to shutdown the service.
            selfHost.Close();
        }
        catch (CommunicationException ce)
        {
            Console.WriteLine("An exception occurred: {0}", ce.Message);
            selfHost.Abort();
        }
    
    }
    
  3. Call Close on the WCF client and wait until the user presses ENTER to terminate the application.

    ' Step 3: Closing the client gracefully closes the connection and cleans up resources.
    Client.Close()
    
    Console.WriteLine()
    Console.WriteLine("Press <ENTER> to terminate client.")
    Console.ReadLine()
    
    //Step 3: Closing the client gracefully closes the connection and cleans up resources.
    client.Close();
    
    
    Console.WriteLine();
    Console.WriteLine("Press <ENTER> to terminate client.");
    Console.ReadLine();
    

Example

The following example shows you how to create a WCF client, how to call the operations of the client, and how to close the client once the operation call is completed.

Compile the generated WCF client and the following code example into an executable named Client.exe. Be sure to reference System.ServiceModel when compiling the code.

Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.ServiceModel


Module Client

    Sub Main()
        ' Step 1: Create an endpoint address and an instance of the WCF Client.
        Dim epAddress As New EndpointAddress("https://localhost:8000/ServiceModelSamples/Service/CalculatorService")
        Dim Client As New CalculatorClient(New WSHttpBinding(), epAddress)

        'Step 2: Call the service operations.
        'Call the Add service operation.
        Dim value1 As Double = 100D
        Dim value2 As Double = 15.99D
        Dim result As Double = Client.Add(value1, value2)
        Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result)

        'Call the Subtract service operation.
        value1 = 145D
        value2 = 76.54D
        result = Client.Subtract(value1, value2)
        Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result)

        'Call the Multiply service operation.
        value1 = 9D
        value2 = 81.25D
        result = Client.Multiply(value1, value2)
        Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result)

        'Call the Divide service operation.
        value1 = 22D
        value2 = 7D
        result = Client.Divide(value1, value2)
        Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result)

        ' Step 3: Closing the client gracefully closes the connection and cleans up resources.
        Client.Close()

        Console.WriteLine()
        Console.WriteLine("Press <ENTER> to terminate client.")
        Console.ReadLine()

    End Sub
End Module
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;

namespace ServiceModelSamples
{

    class Client
    {
        static void Main()
        {
            //Step 1: Create an endpoint address and an instance of the WCF Client.
            CalculatorClient client = new CalculatorClient();


            // Step 2: Call the service operations.
            // Call the Add service operation.
            double value1 = 100.00D;
            double value2 = 15.99D;
            double result = client.Add(value1, value2);
            Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);

            // Call the Subtract service operation.
            value1 = 145.00D;
            value2 = 76.54D;
            result = client.Subtract(value1, value2);
            Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);

            // Call the Multiply service operation.
            value1 = 9.00D;
            value2 = 81.25D;
            result = client.Multiply(value1, value2);
            Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

            // Call the Divide service operation.
            value1 = 22.00D;
            value2 = 7.00D;
            result = client.Divide(value1, value2);
            Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);

            //Step 3: Closing the client gracefully closes the connection and cleans up resources.
            client.Close();
            

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();

        }
    }
}

Ensure the service is running before attempting to use the client. For more information, see How to: Host and Run a Basic Windows Communication Foundation Service.

To launch the client, right-click Client in the Solution Explorer and choose Debug, Start new instance.

Add(100,15.99) = 115.99
Subtract(145,76.54) = 68.46
Multiply(9,81.25) = 731.25
Divide(22,7) = 3.14285714285714
Press <ENTER> to terminate client.

If you see this output, you have successfully completed the tutorial. This sample demonstrates how to configure the WCF client in code. For troubleshooting information, see Troubleshooting the Getting Started Tutorial.

See Also

Tasks

How to: Create a Windows Communication Foundation Client
How to: Create a Duplex Contract
How to: Access Services with a Duplex Contract
Getting Started Sample
Self-Host

Other Resources

Building Clients
Getting Started Tutorial
Basic WCF Programming