MSDN上發現了一篇很好的WCF入門教程

看了園子裏很多學習WCF的例子,感覺受益匪淺,但是由於每個人學習的側重點不同,一些很詳細的細節例如每一個屬性都是用來幹什麼的,建立不同的項目類型對創建的服務有什麼區別等等,都不得而知。終於,在MSDN上發現了一篇入門教程。講解的十分基本,十分詳細,想進到每一個細節,然我徹底瞭解入門的每一個細節,整個教程結構清晰,代碼簡潔,講解細緻,值得推薦。

地址: http://msdn.microsoft.com/en-us/library/ms734712.aspx

做這分5部來講解創建一個最基本的基於B/S構架的WCF應用。服務是根據輸入的兩個數字,返回這兩個數字的加減乘除運算結果。

第一步:定義WCF服務契約(創建項目,加入引用,定義Interface)
第二部:引入WCF服務契約(添加具體服務函數)
第三部:構架WCF服務,運行WCF服務(添加Uri,定義服務對象地址,運行服務)
第四部:利用工具訪問服務,自動生成WCF服務代理的代碼文件
第五部:配置一個簡單的WCF客戶端(用客戶端引入服務代理,通過服務代理來訪問服務)
第六部:運行程序
How to: Define a Windows Communication Foundation Service Contract
How to: Implement a Windows Communication Foundation Service Contract
How to: Host and Run a Basic Windows Communication Foundation Service
How to: Create a Windows Communication Foundation Client
How to: Configure a Basic Windows Communication Foundation Client
How to: Use a Windows Communication Foundation Client
先建立一個解決方案。
在這個解決方案下面建立一個叫做Server的控制檯應用項目,再建立一個叫做Client的控制檯應用項目。
分別給每一個項目添加引用到System.ServiceModel
編輯每個項目下面的Program.cs
 
using System;  
using System.ServiceModel;  
using System.ServiceModel.Description;  
  
namespace Microsoft.ServiceModel.Samples  
{  
    // Define a service contract.   
    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]  
    public interface ICalculator  
    {  
        [OperationContract]  
        double Add(double n1, double n2);  
        [OperationContract]  
        double Subtract(double n1, double n2);  
        [OperationContract]  
        double Multiply(double n1, double n2);  
        [OperationContract]  
        double Divide(double n1, double n2);  
    }  
  
    // Service class that implements the service contract.   
    // Added code to write output to the console window.   
    public class CalculatorService : ICalculator  
    {  
        public double Add(double n1, double n2)  
        {  
            double result = n1 + n2;  
            Console.WriteLine("Received Add({0},{1})", n1, n2);  
            Console.WriteLine("Return: {0}", result);  
            return result;  
        }  
  
        public double Subtract(double n1, double n2)  
        {  
            double result = n1 - n2;  
            Console.WriteLine("Received Subtract({0},{1})", n1, n2);  
            Console.WriteLine("Return: {0}", result);  
            return result;  
        }  
  
        public double Multiply(double n1, double n2)  
        {  
            double result = n1 * n2;  
            Console.WriteLine("Received Multiply({0},{1})", n1, n2);  
            Console.WriteLine("Return: {0}", result);  
            return result;  
        }  
  
        public double Divide(double n1, double n2)  
        {  
            double result = n1 / n2;  
            Console.WriteLine("Received Divide({0},{1})", n1, n2);  
            Console.WriteLine("Return: {0}", result);  
            return result;  
        }  
    }  
  
  
    class Program  
    {  
        static void Main(string[] args)  
        {  
  
            // Step 1 of the address configuration procedure: Create a URI to serve as the base address.   
            Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");  
  
            // Step 1 of the hosting procedure: Create ServiceHost   
            ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);  
            try  
            {  
  
  
                // Step 3 of the hosting procedure: Add a service endpoint.   
                selfHost.AddServiceEndpoint(  
                   typeof(ICalculator),  
                   new WSHttpBinding(),  
                    "CalculatorService");  
  
  
                // Step 4 of the hosting procedure: Enable metadata exchange.   
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();  
                smb.HttpGetEnabled = true;  
                selfHost.Description.Behaviors.Add(smb);  
  
                // Step 5 of the hosting procedure: Start (and then stop) the service.   
                selfHost.Open();  
                Console.WriteLine("The service is ready.");  
                Console.WriteLine("Press <ENTER> to terminate service.");  
                Console.WriteLine();  
                Console.ReadLine();  
  
                // Close the ServiceHostBase to shutdown the service.   
                selfHost.Close();  
            }  
            catch (CommunicationException ce)  
            {  
                Console.WriteLine("An exception occurred: {0}", ce.Message);  
                selfHost.Abort();  
            }  
        }  
    }  
}  
 
服務端創建好了以後,就可以試運行了。
這時候可以用微軟提供的命令行工具訪問這個服務,生成服務代理 app.config 和 generatedProxy.cs兩個文件。

PATH=C:/WINDOWS/Microsoft.NET/Framework/v3.5

DataSvcUtil.exe /language:csharp /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service

注意:實在server運行的時候,生成包裝類。

當然,如果是已經運行的服務,可以使用VS引用就行了。

把這兩個文件添加到客戶端項目裏去。
現在就可以編輯客戶端代碼了。

using System;  
using System.Collections.Generic;  
using System.Text;  
using System.ServiceModel;  
  
namespace ServiceModelSamples  
{  
  
    class Client  
    {  
        static void Main()  
        {  
            //Step 1: Create an endpoint address and an instance of the WCF Client.   
            EndpointAddress epAddress = new EndpointAddress("http://localhost:8000/ServiceModelSamples/Service/CalculatorService");  
            CalculatorClient client = new CalculatorClient(new WSHttpBinding(), epAddress);  
  
  
            // Step 2: Call the service operations.   
            // Call the Add service operation.   
            double value1 = 100.00D;  
            double value2 = 15.99D;  
            double result = client.Add(value1, value2);  
            Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);  
  
            // Call the Subtract service operation.   
            value1 = 145.00D;  
            value2 = 76.54D;  
            result = client.Subtract(value1, value2);  
            Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);  
  
            // Call the Multiply service operation.   
            value1 = 9.00D;  
            value2 = 81.25D;  
            result = client.Multiply(value1, value2);  
            Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);  
  
            // Call the Divide service operation.   
            value1 = 22.00D;  
            value2 = 7.00D;  
            result = client.Divide(value1, value2);  
            Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);  
  
            //Step 3: Closing the client gracefully closes the connection and cleans up resources.   
            client.Close();  
  
            Console.WriteLine();  
            Console.WriteLine("Press <ENTER> to terminate client.");  
            Console.ReadLine();  
  
  
        }  
    }  
}  

每一個細節都包含在上面的這兩個Program.cs文件中了,你大概看一下就會懂。比院子裏大多數教材說得都清晰,特別適合像我一樣愛刨根問底的初學者。:)
最後編譯程序,試運行。(兩個都是命令行程序,直接到那個編譯好的目錄裏去找那個exe文件運行,先運行服務,再運行客戶端)。


 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章