WCF客户端主要提供两方面的功能。一方面,将客户端服务调用请求从方法调用形式转换为消息形式,并将编码后的消息通过相应的传输协议发送到服务端;另一方面,对从传输层接受的回复消息进行解码转换成消息对象,并从回复消息对象中提取服务操作执行的结果,将其转换成服务调用方法的返回值,或者输出或者引用参数。我们通过ChannelFactory<TChannel>创建的服务代理进行服务调用,而ClientBase<TChannel>在内部也是通过前者创建于服务调用的服务代理的。
1、ChannelFactory<TChannel>的核心是终结点
通过寄宿我们将服务以终结点的形式暴露出来供潜在的客户端消费,客户端着通过与之匹配的终结点进行服务调用。一个与服务匹配的客户端终结点是确保服务正常调用的必要条件,而创建用于服务调用的代理工厂ChannelFactory<TChannel>的核心就是代表终结点的ServiceEndpoint对象。
表示终结点的ServiceEndpoint对象是ChannelFactory<TChannel>的核心,所以在创建一个ChannelFactory<TChannel>的时候要么直接指定一个ServiceEndpoint对象,要么分别指定构成终结点的三元素。
2、通过ClientBase<TChannel>创建服务代理对象
2.1 在客户端层创建CalculatorClient.cs,客户端服务代理对象类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Client1
{
/// <summary>
/// 契约接口
/// </summary>
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double x, double y);
[OperationContract]
double Subtract(double x, double y);
[OperationContract]
double Multiply(double x, double y);
[OperationContract]
double Divide(double x, double y);
}
/// <summary>
/// 服务代理类
/// </summary>
public 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 x, double y)
{
return base.Channel.Add(x, y);
}
public double Subtract(double x, double y)
{
return base.Channel.Subtract(x, y);
}
public double Multiply(double x, double y)
{
return base.Channel.Multiply(x, y);
}
public double Divide(double x, double y)
{
return base.Channel.Divide(x, y);
}
}
}
2.2 客户端调用服务
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace Client1
{
class Program
{
static void Main(string[] args)
{
BasicHttpBinding bind = new BasicHttpBinding();
bind.Security.Mode = BasicHttpSecurityMode.None;
EndpointAddress edp = new EndpointAddress("http://127.0.0.1:3721/CalculatorService");
using (CalculatorClient client = new CalculatorClient(bind, edp))
{
double result = client.Add(3, 4);
Console.Write(result);
}
Console.Read();
}
}
}
注意:服务调用完成后记得关闭代理对象哦。