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"); }