一、参考http://www.cnblogs.com/artech/archive/2007/02/26/656901.html
二、步骤
1、新建空白解决方案:文件--新建项目--其他项目类型--Visual Studio解决方案--空白解决方案
2、新建契约类库项目 Contract,引用System.ServiceModel; 新建接口ICalculator,代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace Contract { [ServiceContract(Name="CalculatorService",Namespace="http://www.artech.com/")] public interface ICalculator { [OperationContract] double Add(double x,double y); } }
3、新建服务类库项目Service,引用Contract,新建类CalculatorService,代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Contract; namespace Service { public class CalculatorService : ICalculator { public double Add(double x, double y) { return x + y; } } }
4、新建寄宿服务的控制台项目Hosting,引用System.ServiceModel、Service、Contract,代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using Service; namespace Hosting { class Program { static void Main(string[] args) { ServiceHost host = new ServiceHost(typeof(Service.CalculatorService)); host.Opened += delegate { Console.WriteLine("服务已经启动,按任意键结束!"); }; host.Open(); Console.ReadLine(); } } }
配置服务文件,添加配置文件(添加-新建项-常规-应用程序配置文件),配置服务终结点,配置如下:
终结点(EndPoint)三要素:地址Address(决定服务位置),绑定Binding(实现通信的细节),契约Contract(对服务操作的抽象)
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="metadataBehavior"> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:9999/CalculatorService/metadata" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="metadataBehavior" name="Service.CalculatorService"> <!--注意此处必须与第三步服务的命名空间一致--> <endpoint address="http://127.0.0.1:9999/CalculatorService" binding="wsHttpBinding" contract="Contract.ICalculator" /> </service> </services> </system.serviceModel> </configuration>
4、客户端调用,新建控制台项目Client
4.1 运行Hosting.exe,
4.2 引用--添加服务引用,地址中输入http://127.0.0.1:9999/CalculatorService/metadata--前往,命名空间:ServiceReference,
http://127.0.0.1:9999/CalculatorService/metadata 为WSDL形式体现的服务元数据,可以在IE中打开查看
4.3 添加代码如下。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using Client.ServiceReference; namespace Client { class Program { static void Main(string[] args) { System.Threading.Thread.Sleep(5*1000); //等待服务启动后再调用 ServiceCalculatorClient client = new ServiceCalculatorClient(); Console.WriteLine("x+y={0},when x={1} and y={2}",client.Add(1,2),1,2); Console.ReadLine(); } } }
5、设置client、hosting为启动项(解决方案--右键--属性-多启动项-client启动、hosting启动),F5运行 查看结果。
6、源代码下载
时间: 2024-11-09 15:55:52