WCF服务调用可以采用两个方法,由工具SvcUtil.exe生成本地代理服务类和配置文件方式,或者采用ChannelFactory直接创建服务代理对象。本文主要采用前面一种方式来进行。
SvcUtil.exe位于:C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin目录下,可以将本工具添加到VS2010的工具菜单中,以方便使用:
VS菜单-》工具-》外部工具-》添加-》在“命令”文本框选取其路径如下:C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcUtil.exe,在初始目录(这里是配置文件和代理类生成后放置的地方),我们选取“$(SolutionDir)”。
添加完成后,工具下拉菜单会出现SvcUtil,如何使用呢?
首先,对于Http类型的Uri来说,很容易搞定,直接在SvcUtil的输入框输入类似:http://localhost:22222/calService/metadata即可生成服务器端在客户端的代理类和配置文件,然后将这两个文件拷到项目中并将output.config改名为app.config就可以了。
如果遇到net.tcp(比如:net.tcp://localhost:22222/chatservice)该怎么进行呢?
其实很简单,我们只需要在服务入口处添加Service的EndPoint即可。
Uri uri = new Uri(ConfigurationManager.AppSettings["addr"]); using(ServiceHost host = new ServiceHost(typeof(NikeSoftChat.ChatService),uri)) { ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>(); if (smb == null) { host.Description.Behaviors.Add(new ServiceMetadataBehavior()); } host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); host.Open(); Console.WriteLine("Chat service listen on endpoint {0}", uri.ToString()); Console.WriteLine("Press ENTER to stop chat service..."); Console.ReadLine(); host.Abort(); host.Close(); }
注意,黄色标记很重要,它能够暴露出元数据出来,如果没有黄色标记部分,利用SvcUtil生成net.tcp的代理类和配置文件将是不可能的。
然后,将net.tcp://localhost:22222/chatservice输入SvcUtil.exe的输入框,然后点击生成,显示信息如下:
Microsoft (R) Service Model Metadata Tool [Microsoft (R) Windows (R) Communication Foundation,版本 3.0.4506.2152] 版权所有(c) Microsoft Corporation。保留所有权利。 正在尝试使用 WS-Metadata Exchange 从“net.tcp://localhost:22222/chatservice”下载元数据。此 URL 不支持 DISCO。 正在生成文件... E:\WCF\WCF_ChatRoom\ChatService.cs E:\WCF\WCF_ChatRoom\output.config 请按任意键继续. . .
然后生成的文件为:ChatService.cs和output.config,内容如下:
ChatService.cs
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:2.0.50727.5456 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")] [System.ServiceModel.ServiceContractAttribute(ConfigurationName="IChat", CallbackContract=typeof(IChatCallback), SessionMode=System.ServiceModel.SessionMode.Required)] public interface IChat { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IChat/Join", ReplyAction="http://tempuri.org/IChat/JoinResponse")] string[] Join(string name); [System.ServiceModel.OperationContractAttribute(IsOneWay=true, IsInitiating=false, Action="http://tempuri.org/IChat/Say")] void Say(string msg); [System.ServiceModel.OperationContractAttribute(IsOneWay=true, IsInitiating=false, Action="http://tempuri.org/IChat/Whisper")] void Whisper(string to, string msg); [System.ServiceModel.OperationContractAttribute(IsOneWay=true, IsTerminating=true, IsInitiating=false, Action="http://tempuri.org/IChat/Leave")] void Leave(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")] public interface IChatCallback { [System.ServiceModel.OperationContractAttribute(IsOneWay=true, Action="http://tempuri.org/IChat/Receive")] void Receive(string senderName, string message); [System.ServiceModel.OperationContractAttribute(IsOneWay=true, Action="http://tempuri.org/IChat/ReceiveWhisper")] void ReceiveWhisper(string senderName, string message); [System.ServiceModel.OperationContractAttribute(IsOneWay=true, Action="http://tempuri.org/IChat/UserEnter")] void UserEnter(string name); [System.ServiceModel.OperationContractAttribute(IsOneWay=true, Action="http://tempuri.org/IChat/UserLeave")] void UserLeave(string name); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")] public interface IChatChannel : IChat, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")] public partial class ChatClient : System.ServiceModel.DuplexClientBase<IChat>, IChat { public ChatClient(System.ServiceModel.InstanceContext callbackInstance) : base(callbackInstance) { } public ChatClient(System.ServiceModel.InstanceContext callbackInstance, string endpointConfigurationName) : base(callbackInstance, endpointConfigurationName) { } public ChatClient(System.ServiceModel.InstanceContext callbackInstance, string endpointConfigurationName, string remoteAddress) : base(callbackInstance, endpointConfigurationName, remoteAddress) { } public ChatClient(System.ServiceModel.InstanceContext callbackInstance, string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(callbackInstance, endpointConfigurationName, remoteAddress) { } public ChatClient(System.ServiceModel.InstanceContext callbackInstance, System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(callbackInstance, binding, remoteAddress) { } public string[] Join(string name) { return base.Channel.Join(name); } public void Say(string msg) { base.Channel.Say(msg); } public void Whisper(string to, string msg) { base.Channel.Whisper(to, msg); } public void Leave() { base.Channel.Leave(); } }
output.config:
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.serviceModel> <bindings> <netTcpBinding> <binding name="NetTcpBinding_IChat" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10" maxReceivedMessageSize="65536"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="true" /> <security mode="None"> <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" /> <message clientCredentialType="Windows" /> </security> </binding> </netTcpBinding> </bindings> <client> <endpoint address="net.tcp://localhost:22222/chatservice" binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IChat" contract="IChat" name="NetTcpBinding_IChat" /> </client> </system.serviceModel> </configuration>
然后将ChatService.cs放入客户端的工程文件中,output.config改名为App.config,放到服务器端的工程文件中即可。