实例是一个控制台服务,实现客户端调用服务中的加减乘除方法的简单实例。包含服务和客户端
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.ServiceModel;using System.ServiceModel.Description;namespace WCFService{ //服务协定是描述服务需要实现的一系列接口,接口中定义需要实现的方法及对各个方法的属性描述 //定义服务协定 //ServiceContract是用来标注该接口是服务协定 [ServiceContract(Namespace = "http://VS2017.WCF.Sample")] //服务接口 public interface IService { //加操作方法 [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); } //实现接口的方法 public class CalculatorService : IService { public double Add(double n1,double n2) { double result = n1 n2; Console.WriteLine("调用方法Add({0},{1})", n1, n2); Console.WriteLine("返回:{0}", result); return result; } public double Subtract(double n1, double n2) { double result = n1 - n2; Console.WriteLine("调用方法Add({0},{1})", n1, n2); Console.WriteLine("返回:{0}", result); return result; } public double Multiply(double n1, double n2) { double result = n1 * n2; Console.WriteLine("调用方法Add({0},{1})", n1, n2); Console.WriteLine("返回:{0}", result); return result; } public double Divide(double n1, double n2) { double result = n1 / n2; Console.WriteLine("调用方法Add({0},{1})", n1, n2); Console.WriteLine("返回:{0}", result); return result; } } class Program { static void Main(string[] args) { //创建基本地址 Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service"); //创建服务主机 ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress); try { //创建服务终结点 selfHost.AddServiceEndpoint(typeof(IService), new WSHttpBinding(), "CalculatorService"); //激活元数据交换 ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true;//启用HttpGet selfHost.Description.Behaviors.Add(smb);//添加元数据 selfHost.Open(); //启动服务 //在控制台显示运行信息 Console.WriteLine("服务已经启动"); Console.WriteLine("按<enter>键终止服务"); Console.WriteLine(); Console.ReadLine(); //终止服务 selfHost.Close(); } catch(CommunicationException e) { Console.WriteLine("异常:{0}", e.Message); Console.ReadLine(); //调用终止服务的方法 selfHost.Abort(); } } }}
评论