WCF在通訊過程當中有三種模式:請求與答覆、單向、雙工通訊。html
請求與答覆模式web
描述:客戶端發送請求,而後一直等待服務端的響應(異步調用除外),期間處於假死狀態,直到服務端有了答覆後才能繼續執行其餘程序服務器
請求與答覆模式爲WCF的默認模式,以下代碼所示:異步
[OperationContract] string ShowName(string name);
即便返回值是void 也屬於請求與答覆模式。spa
缺點:若是用WCF在程序A中上傳一個2G的文件,那麼要想執行程序B也許就是幾個小時後的事情了。若是操做須要很長的時間,那麼客戶端程序的響應能力將會大大的降低。htm
優勢:有返回值咱們就能夠向客戶端返回錯誤信息,如:只接收".rar"文件等信息。blog
單向模式接口
描述:客戶端向服務端發送求,可是無論服務端是否執行完成就接着執行下面的程序。ip
單向模式要在OpertaionContract的屬性中顯示設置值,代碼以下:string
[OperationContract(IsOneWay = true)] void ShowName(string name);
優缺點與「請求響應模式」差很少倒過來。
特色:使用 IsOneWay=true 標記的操做不得聲明輸出參數、引用參數或返回值。
雙工模式
描述:雙工模式創建在答覆模式和單向模式的基礎之上,實現客戶端與服務端相互的調用。
相互調用:以往咱們只是在客戶端調用服務端,而後服務端有返回值返回客戶端,而相互調用不光是客戶端調用服務端,並且服務端也能夠調用客戶端的方法。
1.添加WCF服務 Service2.svc,並定義好回調的接口,服務器端接口IService2.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace WcfService1 { //CallbackContract = typeof(IService2CallBack) 定義回調的接口類型 [ServiceContract(CallbackContract = typeof(IService2CallBack))] public interface IService2 { [OperationContract] string ShowName(string name); } //回調的接口,該接口中的方法在客戶端實現 public interface IService2CallBack { //IsOneWay = true 啓動單向模式,該模式方法不能有返回值 [OperationContract(IsOneWay = true)] void PrintSomething(string str); } }
2.服務端實現 Service2.svc
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace WcfService1 { public class Service2 : IService2 { IService2CallBack callback = null;//回調接口類型 public Service2() { //獲取調用當前操做的客戶端實例 callback = OperationContext.Current.GetCallbackChannel<IService2CallBack>(); } /// <summary> /// 被客戶端調用的服務 /// </summary> /// <param name="name"></param> /// <returns></returns> public string ShowName(string name) { callback.PrintSomething(name); return "服務器調用客戶端,WCF服務,顯示名稱:xsj..."; } } }
3.服務器端配置,web.config 在system.serviceModel中添加配置,
支持回調的綁定有4種:WSDualHttpBinding、NetTcpBinding、NetNamedPipeBinding、NetPeerTcpBinding。
咱們這裏用WSDualHttpBinding爲例:
<endpoint address="" binding="wsDualHttpBinding" contract="WcfService1.IService2"></endpoint>
<system.serviceModel> <services> <service name="WcfService1.Service2"> <endpoint address="" binding="wsDualHttpBinding" contract="WcfService1.IService2"></endpoint> </service> </services> </system.serviceModel>
4.客戶端調用
class Program { static void Main(string[] args) { InstanceContext instanceContext = new InstanceContext(new CallbackHandler()); Service2Client client = new Service2Client(instanceContext); string result = client.ShowName("jay.xing"); Console.WriteLine(result); Console.ReadLine(); } } //實現服務端的回調接口 public class CallbackHandler : IService2Callback { public void PrintSomething(string str) { Console.WriteLine("test data:" + str); } }
介紹結束,參考:http://www.cnblogs.com/iamlilinfeng/archive/2012/10/03/2710698.html