作為微軟技術.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(); } } } 就可以獲取得到服務器的對象了