作為微軟技術(shù).net 3.5的三大核心技術(shù)之一的WCF雖然沒有WPF美麗的外觀
但是它卻是我們開發(fā)分布式程序的利器
但是目前關(guān)于WCF方面的資料相當(dāng)稀少
希望我的這一系列文章可以幫助大家盡快入門
下面先介紹一下我的開發(fā)環(huán)境吧
操作系統(tǒng):windows vista business版本
編譯器:Visual Studio 2008(英文專業(yè)版)
WCF的三大核心是ABC
也就是A代表Address-where(對(duì)象在哪里)
B代表Binding-how(通過什么協(xié)議取得對(duì)象)
C代表Contact(契約)-what(定義的對(duì)象是什么,如何操縱)
其他的理論知識(shí)大家可以參見《Programming WCF Service》
或者今年3月份剛剛出版的《Essential Windows Commmunication Foundation》
現(xiàn)在用In Action的方式來(lái)手把手教大家創(chuàng)建第一個(gè)WCF程序
首先如下圖所示創(chuàng)建一個(gè)空的解決方案
接下來(lái)右鍵點(diǎn)擊解決方案HelloWCF選擇Add->New Project并選擇Console Application模板并選擇名為項(xiàng)目名為Host(服務(wù)器端)
接下來(lái)右鍵點(diǎn)擊Host項(xiàng)目選擇Add->New Item并選擇Webservice模板(文件命名為HelloWCFService)
將創(chuàng)建三個(gè)文件IHelloWCFService.cs,HelloWCFService.cs以及App.config文件
IHelloWCFService.cs代碼如下
using System.ServiceModel;
namespace Host
{
[ServiceContract]
public interface IHelloWCFService
{
[OperationContract]
string HelloWCF(string message);
}
}
而HelloWCFService.cs代碼實(shí)現(xiàn)如下
using System;
namespace Host
{
public class HelloWCFService : IHelloWCFService
{
public string HelloWCF(string message)
{
return string.Format("你在{0}收到信息:{1}",DateTime.Now,message);
}
}
}
App.config文件原則上可以不用改,但是address太長(zhǎng)了
(默認(rèn)的為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文件
接下來(lái)創(chuàng)建客戶端程序?yàn)镃onsole Application項(xiàng)目Client
啟動(dòng)Host.exe文件
右鍵點(diǎn)擊Client項(xiàng)目并選擇Add Service Reference...
并且在Address的TextBox里面輸入服務(wù)器的地址(就是咱們前面設(shè)置的baseaddress地址),并點(diǎn)擊Go
將得到目標(biāo)服務(wù)器上面的Services,如下圖所示
這一步見在客戶端間接借助SvcUtil.exe文件創(chuàng)建客戶端代理(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("歡迎來(lái)到WCF村!");
Console.WriteLine(str);
Console.ReadLine();
}
}
}
就可以獲取得到服務(wù)器的對(duì)象了
如對(duì)本文有疑問,請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答??! 點(diǎn)擊進(jìn)入論壇