WCF教程系列(1)-創建第一個WCF程序

原文地址爲: WCF教程系列(1)-創建第一個WCF程序

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


轉載請註明本文地址: WCF教程系列(1)-創建第一個WCF程序