單向模式(One-Way Calls):
- 在這種交換模式中,存在着如下的特征:
- 只有客戶端發起請求,服務端並不會對請求進行回復
- 不能包含ref或者out類型的參數
- 沒有返回值,返回類型只能為void
- 通過設置OperationContract的IsOneWay=True可以將滿足要求的方法設置為這種消息交換模式
接下來,我們通過實例來演示這種模式,首先新建一個WcfDemo1的解決方案,添加名稱為Service的類庫項目作為服務端,新建IOneWay接口和 OneWay類,由於單向模式中服務端並不會有返回操作,所以我們可以用線程時間來模擬客戶端對服務端的調用情況。總個工程的結構如下:
服務契約接口中的代碼如下:
using System.ServiceModel; namespace Service { [ServiceContract] public interface IOneWay { [OperationContract(IsOneWay=true)] void SayHello(string name); } }
服務契約的實現代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Service { public class OneWay:IOneWay { public void SayHello(string name) { System.Threading.Thread.Sleep(10000); } } }
接下來我們將服務寄宿起來,Host中的配置文件代碼如下:
<?xmlversion="1.0"?> <configuration> <system.serviceModel> <services> <servicename="Service.OneWay"behaviorConfiguration="OneWayBehavior"> <host> <baseAddresses> <addbaseAddress="http://127.0.0.1:1234/OneWay/"/> </baseAddresses> </host> <endpoint address=""binding="wsHttpBinding" contract="Service.IOneWay"/> <endpoint address="mex"binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behaviorname="OneWayBehavior"> <serviceMetadatahttpGetEnabled="True"/> <serviceDebugincludeExceptionDetailInFaults="True"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
Program.cs中的代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using Service; namespace Host { class Program { static void Main(string[] args) { using (ServiceHost oneWayHost = newServiceHost(typeof(OneWay))) { oneWayHost.Opened += delegate { Console.WriteLine("單向通訊服務已經啟動,按任意鍵終止!"); }; oneWayHost.Open(); Console.Read(); } } } }
到此,我們完成了對服務的寄宿,啟動Host.exe,在瀏覽器中輸入http://127.0.0.1:1234/OneWay/我們可以看到寄宿成功的頁面。在客戶端添加服務引用:
引用后在客戶端程序添加以下代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Client.OneWayServiceRef; namespace Client { class Program { static void Main(string[] args) { Console.WriteLine("****************單向通訊服務示例*******************"); OneWayClient proxy = newOneWayClient(); Console.WriteLine("方法調用前時間:"+ System.DateTime.Now); proxy.SayHello("WCF"); Console.WriteLine("方法調用后時間:" + System.DateTime.Now); Console.Read(); } } }
生成后運行程序Client.exe,可以看到以下效果:
我們發現前后兩次的時間相同,雖然服務器方法的時間進程暫停了10s,但客戶端的表現出的只是單向的,並沒有等待服務器的時間,也就是服務器並沒有像客戶端發送響應的消息。
以上是我們程序表現出來的結果。接下來,我們通過消息層面說明這個。啟動vs自帶的WCF客戶端驗證程序,在開始菜單中找到如下圖所示的工具:
點擊啟動該命令行,輸入wcftestclient,回車,啟動WCF客戶端測試程序:
在客戶端測試程序中添加服務地址:
點擊對應的方法,點擊調用按鈕,最后我們發現服務器給出了一條提示:
點擊左下角的xml我們可以看到發送的具體消息:
我們發現只有請求消息,沒有返回的消息,說明服務器並沒有對此作出任何反應。
本文通過程序實例和消息層面說明消息交換模式中的單向模式,在接下來的文章中,我將繼續演示消息交換中另外兩只模式:請求/答復(Request/Reply) 、雙工(Duplex)。