1. 创建空白的Solution。然后依次创建下面三个项目
Contracts:类库项目,添加System.ServiceModel的引用。右击添加新建项:WCF服务(DBServices.cs),删掉App.config。
Host:控制台项目,添加System.ServiceModel和对Contracts项目的引用。
Client:控制台项目,添加System.ServiceModel。
2. 在Contracts项目中IDBServices定义服务契约接口
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace Contracts { // 注意: 如果更改此处的接口名称 "IDBServices",也必须更新 App.config 中对 "IDBServices" 的引用。 [ServiceContract] public interface IDBServices { [OperationContract] void DoWork(); } }
3. 在Contracts项目中实现DBServices接口
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace Contracts { // 注意: 如果更改此处的类名 "DBServices",也必须更新 App.config 中对 "DBServices" 的引用。 public class DBServices : IDBServices { static int count = 0; public void DoWork() { Console.WriteLine("WCF {0}({1})!", count.ToString(), DateTime.Now); count++; } } }
4. 在Host项目中Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using Contracts; using System.ServiceModel.Description; namespace Host { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(DBServices), new Uri("http://localhost:8901/DBServices/"))) { host.AddServiceEndpoint(typeof(IDBServices), new BasicHttpBinding(), "SVC"); if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null) { ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; behavior.HttpGetUrl = new Uri("http://localhost:8901/DBServices/"); host.Description.Behaviors.Add(behavior); } host.Open(); Console.WriteLine("Start Your Service."); Console.ReadKey(); host.Close(); } } } }
5. 生成解决方案。在文件夹路径\Host\bin\Debug下,双击Host.exe。此时在你浏览器地址栏中输入http://127.0.0.1:8901/DBServices/,出现效果如下
出现此图说明你的服务器已经OK了,下面进行客户端的配置。
6. 接着,在Client项目上右击,Add Service Reference。接着如下图(保持前面的Host项目处于运行状态)
Program.cs代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace Client { class Program { static int count = 0; static void Main(string[] args) { while (true) { try { using (DBServiceReference.DBServicesClient client = new Client.DBServiceReference.DBServicesClient()) { while (true) { client.DoWork(); Thread.Sleep(1000); } } } catch (Exception e) { Console.WriteLine("第{0}次错误({1}):{2}", count, DateTime.Now, e.Message); count++; } } } } }
7. 生成解决方案。在文件夹路径\Client\bin\Debug下,双击Client.exe,后台效果图如下