通过新建--》项目----》WCF-》WCF服务库,新建WCF项目,如下图
新建立的项目就是如图中的样子,这个就是一个SCF服务,现在他是可以运行的而且也可以通过连接得到其发布的服务
IService1.cs---------这个文件是服务的合约(或者叫其他称呼)
Service1.cs--------这个是合约的实现
默认的合约和实现中已经包含了一个方法,如下:
合约
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WcfNewDemo
{
// 注意: 如果更改此处的接口名称“IService1”,也必须更新 App.config 中对“IService1”的引用。
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// 任务: 在此处添加服务操作
}
// 使用下面示例中说明的数据协定将复合类型添加到服务操作
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
}
实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WcfNewDemo
{
// 注意: 如果更改此处的类名“IService1”,也必须更新 App.config 中对“IService1”的引用。
[ServiceBehavior]
public class Service1 : IService1
{
[OperationBehavior]
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}
我现在使用winform启动这个服务
1.需要需要建立一个winform的项目........
2.然后将wcf中的配置文件App.config移动到winform的项目中,WCF中的配置文件需要删除或改名
3.winform中添加引用,System.ServiceModel,然后在窗体中添加using System.ServiceModel;+添加对之前的WCF项目的引用
4.在启动按钮的单击事件中添加如下代码,启动服务:
ServiceHost serviceHost = new ServiceHost(typeof (Service1));
serviceHost.Open();
以上代码可以完善,此处只做示例..............
现在单击调试---开始执行(不调试),运行服务器端,然后窗体上的运行按钮,启动WCF服务
新建客户端
新建winform项目
添加服务引用见上图4:
添加后会生成如图5的服务引用;
然后再客户端如是调用:
Service1Client service1Client = new Service1Client();
MessageBox.Show(service1Client.GetData(123)) ;
成功实现WCF..................
这个就是个简单的示例,其实还有许多的东西是通过配置实现的,比如并发什么的,有兴趣的可以看下相关的文章,此处只做简单的示例.