实质:服务说明实质上就是服务相关的一些信息。
1.服务端代码添加了如下黄色代码:
class Program
{
static void Main(string[] args)
{
//创建一个ServiceHost
using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService)))
{
// Open the ServiceHost to create listeners
serviceHost.Open();
Console.WriteLine("服务已经开启!");
Console.WriteLine("按回车键结束服务!");
Console.WriteLine();
Console.ReadLine();
}
} }
[ServiceContract]//定义服务协定完成
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
} [ServiceContract]
public interface ICalculatorSession
{
[OperationContract]
string test(string s); [OperationContract]
string GetServiceDescriptionInfo();
} public class CalculatorService : ICalculator, ICalculatorSession
{
public double Add(double n1, double n2)
{
return n1 + n2;
} public double Subtract(double n1, double n2)
{
return n1 - n2;
} public double Multiply(double n1, double n2)
{
return n1 * n2;
} public double Divide(double n1, double n2)
{
return n1 / n2;
} public string test(string s)
{
return s;
} public string GetServiceDescriptionInfo()
{
StringBuilder sb = new StringBuilder();
OperationContext operationContext = OperationContext.Current;
ServiceHost serviceHost = (ServiceHost)operationContext.Host;
ServiceDescription dec = serviceHost.Description;
sb.Append("Base addresses:\n");
foreach (Uri url in serviceHost.BaseAddresses)
{
sb.Append(" " + url + "\n");
}
sb.Append("Service endpoint:\n");
foreach (ServiceEndpoint endPoint in dec.Endpoints)
{
sb.Append("Address:" + endPoint.Address + "\n");
sb.Append("Binding:" + endPoint.Binding + "\n");
sb.Append("Contract:" + endPoint.Contract + "\n");
} return sb.ToString();
}
}
2.客户端和服务端的配置可前面随笔中的配置
3.客户端的代码:
class Program
{
static void Main(string[] args)
{
CalculatorClient client = new CalculatorClient("secure");
double n1 = 5.6;
double n2 = 7.3;
double result; result = client.Add(n2,n1);
Console.WriteLine("执行加法后的结果为:{0}", result.ToString()); result = client.Subtract(n2, n1);
Console.WriteLine("执行减法后的结果为:{0}", result.ToString()); result = client.Multiply(n1, n2);
Console.WriteLine("执行乘法后的结果为:{0}", result.ToString()); result = client.Divide(n1, n2);
Console.WriteLine("执行除法后的结果为:{0}", result.ToString()); CalculatorSessionClient clientSeesion = new CalculatorSessionClient();
string s = clientSeesion.test("你好我做一个测试!");
string b = clientSeesion.GetServiceDescriptionInfo();
Console.WriteLine(s);
Console.WriteLine(b);
Console.ReadLine(); }
}
4.运行结果如下图: