WCF客户端具体搭建方法解析
来源:互联网 发布:网络教育的考试 编辑:程序博客网 时间:2024/06/16 05:31
搭建WCF客户端,最重要就是要遵循服务端的契约,客户端通过代理(Proxy)来访问服务端点,而并不关心服务端的具体实现。代理要做的就是通过与服务端确认通讯协议,并通过信道(channels)交换数据。在服务端,ServiceHost会为每个端点创建一个信道侦听器,由侦听器产生信道。而客户端代理则产生一个信道发生器,产生客户端信道。只有在服务端信道和客户端信道一致的情况下,双方才允许进行通讯。信道会对通讯过程进行监控,保障通讯的安全性。
为了简单的完成一个WCF客户端,微软为我们准备了一个小工具,就是Service Model MetadataUtility。这个工具能帮你快速的从服务地址中生成客户代理和配置文件。
首先允许服务器端程序,等服务启动后。在VS2008命令行窗口中输入如下命令:svcutil.exehttp://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