一、概述
WCF在通信過程中有三種模式:請求與答復、單向、雙工通信。以下我們一一介紹。
二、請求與答復模式
描述:
客戶端發送請求,然后一直等待服務端的響應(異步調用除外),期間處於假死狀態,直到服務端有了答復后才能繼續執行其他程序
[OperationContract] string ShowName(string name);
二、單向模式
描述:
客戶端向服務端發送求,但是不管服務端是否執行完成就接着執行下面的程序。如下圖所示:
[OperationContract(IsOneWay = true)] void ShowName(string name);
特點:使用 IsOneWay=true 標記的操作不得聲明輸出參數、引用參數或返回值
三、雙工模式
描述:
雙工模式建立在上面兩種模式的基礎之上,實現客戶端與服務端相互的調用。相互調用:以往我們只是在客戶端調用服務端,然后服務端有返回值返回客戶端,而相互調用不光是客戶端調用服務端,而且服務端也可以調用客戶端的方法
在上圖中,客戶端的程序A調用服務端的程序A,服務程序A執行完成前又調用客戶端的程序D,然后再返回到程序A,圖有點亂,其實就是為了說明“服務端”與“客戶端”可以相互調用,下面直接看代碼。
支持回調的綁定有4種:WSDualHttpBinding、NetTcpBinding、NetNamedPipeBinding、NetPeerTcpBinding。我們這里用NetTcpBinding為例
服務端實現方式:
[ServiceContract(CallbackContract =typeof(IDongCallBack))] public interface IPuseService { [OperationContract] string DoWork(string name); }
public class PuseService : IPuseService { public string DoWork(string name) { var callBack= OperationContext.Current.GetCallbackChannel<IDongCallBack>(); callBack.GetName("雙工"+ name); return "WCF服務"; } }
回調接口:
public interface IDongCallBack { [OperationContract(IsOneWay =true)] void GetName(string name); }
//配置文件
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="false" 【有坑,必須改成false】 httpsGetEnabled="false" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="T_WCF.PuseService"> <endpoint address="" binding="netTcpBinding"【必須改】 contract="T_WCF.IPuseService"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexTcpBinding"【必須改】 contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="【必須改】net.tcp://localhost:8733/Design_Time_Addresses/T_WCF/PuseService/" /> </baseAddresses> </host> </service> </services> </system.serviceModel> </configuration>
客戶端實現方式:
class Program { static void Main(string[] args) { InstanceContext instanceContext = new InstanceContext(new CallbackHandler()); PuseServiceClient client = new PuseServiceClient(instanceContext); var result = client.DoWork("wds"); Console.WriteLine(result); Console.ReadKey(); } } class CallbackHandler : IPuseServiceCallback【這個需要F12進入PuseServiceClient,看里面的回調名稱 】
{
public void GetName(string name)
{
Console.WriteLine(name);
}
}