搭建WCF客户端,最重要就是要遵循服务端的契约,客户端通过代理(Proxy)来访问服务端点,而并不关心服务端的具体实现。代理要做的就是通过与服务端确认通讯协议,并通过信道(channels)交换数据。在服务端,ServiceHost会为每个端点创建一个信道侦听器,由侦听器产生信道。而客户端代理则产生一个信道发生器,产生客户端信道。只有在服务端信道和客户端信道一致的情况下,双方才允许进行通讯。信道会对通讯过程进行监控,保障通讯的安全性。
为了简单的完成一个WCF客户端,微软为我们准备了一个小工具,就是Service Model Metadata Utility。这个工具能帮你快速的从服务地址中生成客户代理和配置文件。
首先允许服务器端程序,等服务启动后。在VS2008命令行窗口中输入如下命令:svcutil.exe http://localhost:8080/MyService回车后得到如下页面。
从上面画面中可以看到,wcf为客户端生成了一个客户代理类MyService.cs和一个配置文件output.config。客户端只需要整合这两个文件就可以与服务端通讯了。我们来看看这两个文件的内容:
MyService.cs
//------------------------------------------------------------------------------
//
//
//
//
//
//
//
//------------------------------------------------------------------------------
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute
public interface IMyService
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface IMyServiceChannel : IMyService, System.ServiceModel.IClientChannel
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class MyServiceClient : System.ServiceModel.ClientBase, IMyService
{
}
output.config
从这个文件可以看到,WCF客户端实际上是继承了两个接口,System.ServiceModel.ClientBase< IContract>和IContract。其中IContract是服务端契约的接口;
output.config文件则定义了和服务端匹配的endpoint,有了这两个文件,最后要做的事情就是将其整合到WCF客户端程序中,其步骤如下:
1)建立一个空白解决方案,方案的名称叫MyWCFClient,添加一个名称为MyWCF.Client的ConsoleApplication项目。在该项目中添加System.ServiceModel的引用。
2)另外在方案中再添加一个类库项目,项目名称叫MyWCF.ClientBase,为项目添加System.ServiceModel的引用,类名改为ClientBase。将TemperatureService.cs文件中的代码拷贝到ClientBase中的命名空间引用下。
3)在项目MyWCF.Client项目中添加一个App.config文件,将output.config文件的代码粘贴到该文件中覆盖原来的代码。并为该项目添加对MyWCF.ClientBase项目和System.ServiceModel的引用。
4)在项目MyWCF.Client的Main方法中添加如下代码
注意:自动生成的output.config文件在添加到项目中后要重命名为app.config,否则在实例化代理(proxy)时,会找不到指定的终节点名称和契约!!!
本文文本部分参考:http://developer.51cto.com/art/201002/185219.htm,如有错误,敬请斧正!