서비스를 만든 후 다음 단계는 WCF 클라이언트 프록시를 만드는 것입니다. 클라이언트 애플리케이션은 WCF 클라이언트 프록시를 사용하여 서비스와 통신합니다. 클라이언트 애플리케이션은 일반적으로 서비스의 메타데이터를 가져와서 서비스를 호출하는 데 사용할 수 있는 WCF 클라이언트 코드를 생성합니다.
WCF 클라이언트를 만들기 위한 기본 단계는 다음과 같습니다.
서비스 코드를 컴파일합니다.
WCF 클라이언트 프록시를 생성합니다.
WCF 클라이언트 프록시를 인스턴스화합니다.
서비스 모델 메타데이터 유틸리티 도구(SvcUtil.exe)를 사용하여 WCF 클라이언트 프록시를 수동으로 생성할 수 있습니다. 자세한 내용은 ServiceModel 메타데이터 유틸리티 도구(Svcutil.exe)를 참조하세요. 서비스 참조 추가 기능을 사용하여 Visual Studio 내에서 WCF 클라이언트 프록시를 생성할 수도 있습니다. 두 방법 중 하나를 사용하여 WCF 클라이언트 프록시를 생성하려면 서비스를 실행해야 합니다. 서비스가 자체 호스팅되는 경우 호스트를 실행해야 합니다. 서비스가 IIS/WAS에서 호스트되는 경우 다른 작업을 수행할 필요가 없습니다.
ServiceModel 메타데이터 유틸리티 도구
ServiceModel 메타데이터 유틸리티 도구(Svcutil.exe)는 메타데이터에서 코드를 생성하기 위한 명령줄 도구입니다. 다음 사용은 기본 Svcutil.exe 명령의 예입니다.
Svcutil.exe <service's Metadata Exchange (MEX) address or HTTP GET address>
또는 파일 시스템에서 WSDL(Web Services Description Language) 및 XSD(XML 스키마 정의 언어) 파일과 함께 Svcutil.exe 사용할 수 있습니다.
Svcutil.exe <list of WSDL and XSD files on file system>
결과는 클라이언트 애플리케이션이 서비스를 호출하는 데 사용할 수 있는 WCF 클라이언트 코드가 포함된 코드 파일입니다.
이 도구를 사용하여 구성 파일을 생성할 수도 있습니다.
Svcutil.exe <file1 [,file2]>
파일 이름이 하나만 지정된 경우 출력 파일의 이름입니다. 두 개의 파일 이름이 지정된 경우 첫 번째 파일은 생성된 구성과 콘텐츠가 병합되고 두 번째 파일에 기록되는 입력 구성 파일입니다. 구성에 대한 자세한 내용은 서비스에 대한 바인딩 구성을 참조하세요.
중요합니다
보안되지 않은 메타데이터 요청은 보안되지 않은 네트워크 요청과 동일한 방식으로 특정 위험을 초래합니다. 통신하는 엔드포인트가 누구인지 확실하지 않은 경우 검색하는 정보는 악의적인 서비스의 메타데이터일 수 있습니다.
Visual Studio에서 서비스 참조 추가
서비스가 실행되면 WCF 클라이언트 프록시를 포함할 프로젝트를 마우스 오른쪽 단추로 클릭하고서비스 참조>를 선택합니다. 서비스 참조 추가 대화 상자에서 호출할 서비스에 대한 URL을 입력하고 이동 단추를 클릭합니다. 대화 상자에는 지정한 주소에서 사용할 수 있는 서비스 목록이 표시됩니다. 서비스를 두 번 클릭하여 사용 가능한 계약 및 작업을 확인하고, 생성된 코드에 대한 네임스페이스를 지정하고, 확인 단추를 클릭합니다.
예시
다음 코드 예제에서는 서비스에 대해 만든 서비스 계약을 보여 있습니다.
// Define a service contract.
[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
// Other methods are not shown here.
}
' Define a service contract.
<ServiceContract(Namespace:="http://Microsoft.ServiceModel.Samples")> _
Public Interface ICalculator
<OperationContract()> _
Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double
' Other methods are not shown here.
End Interface
Visual Studio의 ServiceModel 메타데이터 유틸리티 도구 및 서비스 참조 추가 는 다음 WCF 클라이언트 클래스를 생성합니다. 이 클래스는 제네릭 ClientBase<TChannel> 클래스에서 상속되고 인터페이스를 ICalculator
구현합니다. 또한 이 도구는 인터페이스를 ICalculator
생성합니다(여기에 표시되지 않음).
public partial class CalculatorClient : System.ServiceModel.ClientBase<ICalculator>, ICalculator
{
public CalculatorClient()
{}
public CalculatorClient(string endpointConfigurationName) :
base(endpointConfigurationName)
{}
public CalculatorClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{}
public CalculatorClient(string endpointConfigurationName,
System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{}
public CalculatorClient(System.ServiceModel.Channels.Binding binding,
System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress)
{}
public double Add(double n1, double n2)
{
return base.Channel.Add(n1, n2);
}
}
Partial Public Class CalculatorClient
Inherits System.ServiceModel.ClientBase(Of ICalculator)
Implements ICalculator
Public Sub New()
MyBase.New
End Sub
Public Sub New(ByVal endpointConfigurationName As String)
MyBase.New(endpointConfigurationName)
End Sub
Public Sub New(ByVal endpointConfigurationName As String, ByVal remoteAddress As String)
MyBase.New(endpointConfigurationName, remoteAddress)
End Sub
Public Sub New(ByVal endpointConfigurationName As String,
ByVal remoteAddress As System.ServiceModel.EndpointAddress)
MyBase.New(endpointConfigurationName, remoteAddress)
End Sub
Public Sub New(ByVal binding As System.ServiceModel.Channels.Binding,
ByVal remoteAddress As System.ServiceModel.EndpointAddress)
MyBase.New(binding, remoteAddress)
End Sub
Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double
Implements ICalculator.Add
Return MyBase.Channel.Add(n1, n2)
End Function
End Class
WCF 클라이언트 사용
WCF 클라이언트를 사용하려면 다음 코드와 같이 WCF 클라이언트의 인스턴스를 만든 다음 해당 메서드를 호출합니다.
// Create a client object with the given client endpoint configuration.
CalculatorClient calcClient = new CalculatorClient("CalculatorEndpoint");
// Call the Add service operation.
double value1 = 100.00D;
double value2 = 15.99D;
double result = calcClient.Add(value1, value2);
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);
' Create a client object with the given client endpoint configuration.
Dim calcClient As CalculatorClient = _
New CalculatorClient("CalculatorEndpoint")
' Call the Add service operation.
Dim value1 As Double = 100.00D
Dim value2 As Double = 15.99D
Dim result As Double = calcClient.Add(value1, value2)
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result)
클라이언트에서 발생한 예외 디버깅
WCF 클라이언트에서 발생하는 많은 예외는 서비스에 대한 예외 때문에 발생합니다. 다음은 이를 보여주는 몇 가지 예입니다.
SocketException: 기존 연결이 원격 호스트에 의해 강제로 닫혔습니다.
CommunicationException: 기본 연결이 예기치 않게 닫혔습니다.
CommunicationObjectAbortedException: 소켓 연결이 중단되었습니다. 이는 메시지 처리 오류, 원격 호스트에 의해 수신 시간 초과 또는 기본 네트워크 리소스 문제로 인해 발생할 수 있습니다.
이러한 유형의 예외가 발생하면 문제를 해결하는 가장 좋은 방법은 서비스 쪽에서 추적을 켜고 발생한 예외를 확인하는 것입니다. 추적에 대한 자세한 내용은 추적 및 추적을 사용하여 애플리케이션 문제 해결을 참조하세요.