实质:服务说明实质上就是服务相关的一些信息。
1.服务端代码添加了如下黄色代码:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //创建一个ServiceHost 6 using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService))) 7 { 8 // Open the ServiceHost to create listeners 9 serviceHost.Open(); 10 Console.WriteLine("服务已经开启!"); 11 Console.WriteLine("按回车键结束服务!"); 12 Console.WriteLine(); 13 Console.ReadLine(); 14 } 15 } 16 17 } 18 [ServiceContract]//定义服务协定完成 19 public interface ICalculator 20 { 21 [OperationContract] 22 double Add(double n1, double n2); 23 [OperationContract] 24 double Subtract(double n1, double n2); 25 [OperationContract] 26 double Multiply(double n1, double n2); 27 [OperationContract] 28 double Divide(double n1, double n2); 29 } 30 31 [ServiceContract] 32 public interface ICalculatorSession 33 { 34 [OperationContract] 35 string test(string s); 36 37 [OperationContract] 38 string GetServiceDescriptionInfo(); 39 } 40 41 public class CalculatorService : ICalculator, ICalculatorSession 42 { 43 public double Add(double n1, double n2) 44 { 45 return n1 + n2; 46 } 47 48 public double Subtract(double n1, double n2) 49 { 50 return n1 - n2; 51 } 52 53 public double Multiply(double n1, double n2) 54 { 55 return n1 * n2; 56 } 57 58 public double Divide(double n1, double n2) 59 { 60 return n1 / n2; 61 } 62 63 public string test(string s) 64 { 65 return s; 66 } 67 68 public string GetServiceDescriptionInfo() 69 { 70 StringBuilder sb = new StringBuilder(); 71 OperationContext operationContext = OperationContext.Current; 72 ServiceHost serviceHost = (ServiceHost)operationContext.Host; 73 ServiceDescription dec = serviceHost.Description; 74 sb.Append("Base addresses:\n"); 75 foreach (Uri url in serviceHost.BaseAddresses) 76 { 77 sb.Append(" " + url + "\n"); 78 } 79 sb.Append("Service endpoint:\n"); 80 foreach (ServiceEndpoint endPoint in dec.Endpoints) 81 { 82 sb.Append("Address:" + endPoint.Address + "\n"); 83 sb.Append("Binding:" + endPoint.Binding + "\n"); 84 sb.Append("Contract:" + endPoint.Contract + "\n"); 85 } 86 87 return sb.ToString(); 88 } 89 }
2.客户端和服务端的配置可前面随笔中的配置
3.客户端的代码:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 CalculatorClient client = new CalculatorClient("secure"); 6 double n1 = 5.6; 7 double n2 = 7.3; 8 double result; 9 10 result = client.Add(n2,n1); 11 Console.WriteLine("执行加法后的结果为:{0}", result.ToString()); 12 13 result = client.Subtract(n2, n1); 14 Console.WriteLine("执行减法后的结果为:{0}", result.ToString()); 15 16 result = client.Multiply(n1, n2); 17 Console.WriteLine("执行乘法后的结果为:{0}", result.ToString()); 18 19 result = client.Divide(n1, n2); 20 Console.WriteLine("执行除法后的结果为:{0}", result.ToString()); 21 22 CalculatorSessionClient clientSeesion = new CalculatorSessionClient(); 23 string s = clientSeesion.test("你好我做一个测试!"); 24 string b = clientSeesion.GetServiceDescriptionInfo(); 25 Console.WriteLine(s); 26 Console.WriteLine(b); 27 Console.ReadLine(); 28 29 } 30 }
4.运行结果如下图: