为微软技术.net 3.5的三大核心技术之一的WCF虽然没有WPF美丽的外观
但是它却是我们开发分布式程序的利器
但是目前关于WCF方面的资料相当稀少
希望我的这一系列文章可以帮助大家尽快入门
下面先介绍一下我的开发环境吧
操作系统:windows vista business版本
编译器:Visual Studio 2008(英文专业版)
WCF的三大核心是ABC
也就是A代表Address-where(对象在哪里)
B代表Binding-how(通过什么协议取得对象)
C代表Contact(契约)-what(定义的对象是什么,如何操纵)
其他的理论知识大家可以参见《Programming WCF Service》
或者今年3月份刚刚出版的《Essential Windows Commmunication Foundation》
现在用In Action的方式来手把手教大家创建第一个WCF程序
首先如下图所示创建一个空的解决方案

接下来右键点击解决方案HelloWCF选择Add->New Project并选择Console Application模板并选择名为项目名为Host(服务器端)

接下来右键点击Host项目选择Add->New Item并选择Webservice模板(文件命名为HelloWCFService)

将创建三个文件IHelloWCFService.cs,HelloWCFService.cs以及App.config文件
IHelloWCFService.cs代码如下
using System.ServiceModel;
namespace Host
{
??? [ServiceContract]
??? public interface IHelloWCFService
??? {
??????? [OperationContract]
??????? string HelloWCF(string message);
??? }
}
而HelloWCFService.cs代码实现如下
using System;
namespace Host
{
??? public class HelloWCFService : IHelloWCFService
??? {
??????? public string HelloWCF(string message)
??????? {
??????????? return string.Format("你在{0}收到信息:{1}",DateTime.Now,message);
??????? }
??? }
}
App.config文件原则上可以不用改,但是address太长了
(默认的为baseAddress=http://localhost:8731/Design_Time_Addresses/Host/HelloWCFService/)
缩短为baseAddress=http://localhost:8731/HelloWCFService/
并修改Program.cs文件为
using System;
using System.ServiceModel;
namespace Host
{
??? class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? using(ServiceHost host=new ServiceHost(typeof(Host.HelloWCFService)))
??????????? {
??????????????? host.Open();
??????????????? Console.ReadLine();
??????????????? host.Close();
??????????? }
??????? }
??? }
}
编译并生成Host.exe文件
接下来创建客户端程序为Console Application项目Client
启动Host.exe文件
右键点击Client项目并选择Add Service Reference...
并且在Address的TextBox里面输入服务器的地址(就是咱们前面设置的baseaddress地址),并点击Go
将得到目标服务器上面的Services,如下图所示

这一步见在客户端间接借助SvcUtil.exe文件创建客户端代理(using Client.HelloWCF;)以及配置文件app.config
修改客户端的程序如下
using System;
using Client.HelloWCF;
namespace Client
{
??? class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? HelloWCF.HelloWCFServiceClient? proxy=new HelloWCFServiceClient();
??????????? string str = proxy.HelloWCF("欢迎来到WCF村!");
??????????? Console.WriteLine(str);
??????????? Console.ReadLine();
??????? }
??? }
}
就可以获取得到服务器的对象了

原文链接:http://www.pqshow.com/program/aspnet/10752.html