<img src='></a>
作為微軟技術.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();
}
}
}
就可以擷取得到伺服器的對象了