ICalculator.cs代碼以下: 編程
using System.ServiceModel; using System.Collections.Generic; using System.Runtime.Serialization; namespace Service { [ServiceContract] public interface ICalculator { [OperationContract] int Add(int value1, int value2); [OperationContract] int Divide(int value1, int value2); } }
Calculator.cs代碼以下: 安全
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace Service { public class Calculator:ICalculator { public int Add(int value1, int value2) { return value1 + value2; } public int Divide(int value1, int value2) { try { return value1 / value2; } catch(DivideByZeroException) { throw new FaultException("除數不能爲0"); } } } }
2. Host:控制檯應用程序。用來承載服務,添加對於Service程序集的引用後,實現如下代碼就能夠承載服務。網絡
Program.cs的代碼以下:ide
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Service; using System.ServiceModel; namespace Host { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(Calculator))) { host.Opened += delegate { Console.WriteLine("服務已經啓動,按任意鍵終止!"); }; host.Open(); Console.Read(); } } } }
App.config的代碼以下:spa
<?xml version="1.0"?> <configuration> <system.serviceModel> <services> <service name="Service.Calculator" behaviorConfiguration="mexBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:1234/Calculator/"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="Service.ICalculator" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="mexBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
3. Client:控制檯應用程序。將Host承載服務啓動後,客戶端程序添加對服務地址http://localhost:1234/Calculator/的引用,將命名空間設置爲CalculatorServiceRef,3d
接下來咱們就能夠調用服務呢。Client的Program.cs代碼以下:code
首先,咱們將二、3的代碼註釋掉,只驗證服務異常拋出的結果,咱們把Divide的除數設置爲0,此時應該會捕獲到服務端拋出的異常信息。運行結果以下:xml
而後,咱們把一、3註釋,只驗證通信超時的異常拋出。咱們將通道鏈接後的操做時間設置爲很是小的一個值,那麼服務端的運算確定來不及處理,就會拋出超對象
時的異常信息。運行結果以下:blog
最後,咱們將一、2註釋,只驗證通信錯誤異常信息,咱們在客戶端執行完Add()後,就把服務終止,即服務終止鏈接則會拋出通信錯誤的異常信息,運行結果以下所示:
若是此屬性仍然處於打開狀態,則客戶端仍然能夠使用。不然,則應停止客戶端並釋放對其的全部引用。具體參照代碼以下:
if (proxy.State == CommunicationState.Opened){ Console.WriteLine("CommunicationState is Opened"); }