程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> 我的WCF之旅(2):Endpoint Overview

我的WCF之旅(2):Endpoint Overview

編輯:關於.NET

WCF實際上是構建了一個框架,這個框架實現了在互聯系統中各個Application之間如何通信。使得Developers和Architect在構建分布式系統中,無需在考慮如何去實現通信相關的問題,更加關注與系統的業務邏輯本身。而在WCF Infrastructure中,各個Application之間的通信是由Endpoint來實現的。

Endpoint的結構

Endpoint包含以下4個對象:

Address: Address通過一個URI唯一地標識一個Endpoint,並告訴潛在的WCF service的調用者如何找到這個Endpoint。所以Address解決了Where to locate the WCF Service?

Binding: Binding實現在Client和Service通信的所有底層細節。比如Client與Service之間傳遞的Message是如何編碼的——text/XML, binary,MTOM;這種Message的傳遞是采用的哪種Transport——TCP, Http, Named Pipe, MSMQ; 以及采用怎樣的機制解決Secure Messaging的問題——SSL,Message Level Security。所以Binding解決的是How to communicate with service?

Contract: Contract的主要的作用是暴露某個WCF Service所提供的所有有效的Functionality。從Message Exchange的層面上講,Contract實際上是抱每個Operation轉化成為相對應的Message Exchange Pattern——MEP(Request/Response; One-way; Duplex)。所以Contract解決的是What functionalities do the Service provide?

Behavior: Behavior的主要作用是定制Endpoint在運行時的一些必要的Behavior。比如Service 回調Client的Timeout;Client采用的Credential type;以及是否支持Transaction等。

當我們Host一個WCF Service的時候,我們必須給他定義一個或多個Endpoint,然後service通過這個定義的Endpoint進行監聽來自Client端的請求。當我們的Application需要調用這個Service的時候,因為Client 和Service是通過Endpoint的進行通信的, 所以我們必須為我們的Application定義Client端的Endpoint。只有當Client的Endpoint和Service端某個Endpoint相互匹配(Service端可以為一個Service定義多個Endpoint),Client端的請求才能被Service端監聽到。也就是說,我們只有在Client具有一個與Service端完全匹配的Endpoint,我們才能調用這個Service。而這種匹配是比較嚴格的,比如從匹配Address方面,Client端和Service端的Endpoint Address不僅僅在URI上要完全匹配Service, 他們的Headers也需要相互匹配。對於Binding, 一般地,Client需要有一個與Service端完全一樣的Binding,他們之間才能通信。

Sample

首先給一個Sample,以便我們對在WCF Service Aplication中如何定義Endpoint有一個感性的認識。整個Solution的結構參照下圖,我的上一篇Blog([原創]我的WCF之旅(1):創建一個簡單的WCF程序 )中有詳細的介紹。你也可以通過後面的Link下載相應的Source Code(http://www.cnblogs.com/files/artech/Artech.WCFService.zip )

1.Service Contract:Artech..WCfService.Contract/ServiceContract/IGeneralCalculator.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
namespace Artech.WCFService.Contract
{
  [ServiceContract]
  public interface IGeneralCalculator
  {
    [OperationContract]
    double Add(double x, double y);
  }
}

2. Service: Artech.WCFSerice.Service/GeneralCalculatorService.cs

using System;
using System.Collections.Generic;
using System.Text;
using Artech.WCFService.Contract;
namespace Artech.WCFService.Service
{
  public class GeneralCalculatorService:IGeneralCalculator
  {
    IGeneralCalculator Members#region IGeneralCalculator Members
    public double Add(double x, double y)
    {
      return x + y;
    }
    #endregion
  }
}

3. Hosting: Artech.WCFService.Hosting/Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using Artech.WCFService.Contract;
using Artech.WCFService.Service;
using System.ServiceModel.Description;
namespace Artech.WCFService.Hosting
{
  class Program
  {
    static void Main(string[] args)
    {
      //HostCalculatorServiceViaCode();
      HostCalculatorSerivceViaConfiguration();
    }
    /**//// <summary>
    /// Hosting a service using managed code without any configuraiton information.
    /// Please note that the related configuration data should be removed before calling the method.
    /// </summary>
    static void HostCalculatorServiceViaCode()
    {
      Uri httpBaseAddress = new Uri("http://localhost:8888/generalCalculator");
       Uri tcpBaseAddress = new Uri("net.tcp://localhost:9999/generalCalculator");
      using (ServiceHost calculatorSerivceHost = new ServiceHost(typeof(GeneralCalculatorService), httpBaseAddress, tcpBaseAddress))
      {
        BasicHttpBinding httpBinding = new BasicHttpBinding();
        NetTcpBinding tcpBinding = new NetTcpBinding();
        calculatorSerivceHost.AddServiceEndpoint(typeof(IGeneralCalculator), httpBinding, string.Empty);
        calculatorSerivceHost.AddServiceEndpoint(typeof(IGeneralCalculator), tcpBinding, string.Empty);
        ServiceMetadataBehavior behavior = calculatorSerivceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
        {
          if(behavior == null)
          {
            behavior = new ServiceMetadataBehavior();
            behavior.HttpGetEnabled = true;
            calculatorSerivceHost.Description.Behaviors.Add(behavior);
          }
          else
          {
            behavior.HttpGetEnabled = true;
          }
        }
        calculatorSerivceHost.Opened += delegate
        {
          Console.WriteLine("Calculator Service has begun to listen ");
        };
        calculatorSerivceHost.Open();
        Console.Read();
      }
    }
    static void HostCalculatorSerivceViaConfiguration()
    {
      using (ServiceHost calculatorSerivceHost = new ServiceHost(typeof(GeneralCalculatorService)))
      {
        calculatorSerivceHost.Opened += delegate
        {
          Console.WriteLine("Calculator Service has begun to listen ");
        };
        calculatorSerivceHost.Open();
        Console.Read();
      }
    }    
  }
}

4. Service.svc: http://localhost/WCFService/ GeneralCalculatorService.svc

<%@ ServiceHost Language="C#" Debug="true" Service="Artech.WCFService.Service.GeneralCalculatorService" %>

5. Client: Artech.WCFService.Client/ GeneralCalculatorClient.cs & Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Artech.WCFService.Contract;
namespace Artech.WCFService.Client
{
  class GeneralCalculatorClient:ClientBase<IGeneralCalculator>,IGeneralCalculator
  {
    public GeneralCalculatorClient()
      : base()
    { }
    public GeneralCalculatorClient(string endpointConfigurationName)
      : base(endpointConfigurationName)
    { }
    public GeneralCalculatorClient(Binding binding, EndpointAddress address)
      : base(binding, address)
    { }
    IGeneralCalculator Members#region IGeneralCalculator Members
    public double Add(double x, double y)
    {
      return this.Channel.Add(x, y);
    }
    #endregion
  }
}
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Artech.WCFService.Contract;
namespace Artech.WCFService.Client
{
  class Program
  {
    static void Main()
    {
      try
      {
        //InvocateCalclatorServiceViaCode();
        InvocateCalclatorServiceViaConfiguration();
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
      }
      Console.Read();
    }
    static void InvocateCalclatorServiceViaCode()
    {
      Binding httpBinding = new BasicHttpBinding();
      Binding tcpBinding = new NetTcpBinding();
      EndpointAddress httpAddress = new EndpointAddress("http://localhost:8888/generalCalculator");
       EndpointAddress tcpAddress = new EndpointAddress("net.tcp://localhost:9999/generalCalculator");
      EndpointAddress httpAddress_iisHost = new EndpointAddress("http://localhost/wcfservice/GeneralCalculatorService.svc");
       Console.WriteLine("Invocate self-host calculator service ");
      Invocate Self-host service#region Invocate Self-host service
      using (GeneralCalculatorClient calculator_http = new GeneralCalculatorClient(httpBinding, httpAddress))
      {
        using (GeneralCalculatorClient calculator_tcp = new GeneralCalculatorClient(tcpBinding, tcpAddress))
        {
          try
          {
            Console.WriteLine("Begin to invocate calculator service via http transport ");
            Console.WriteLine("x + y = {2} where x = {0} and y = {1}", 1, 2, calculator_http.Add(1, 2));
            Console.WriteLine("Begin to invocate calculator service via tcp transport ");
            Console.WriteLine("x + y = {2} where x = {0} and y = {1}", 1, 2, calculator_tcp.Add(1, 2));
          }
          catch (Exception ex)
          {
            Console.WriteLine(ex.Message);
          }
        }
      }
      #endregion
      Console.WriteLine("\n\nInvocate IIS-host calculator service ");
      Invocate IIS-host service
#region Invocate IIS-host service
      using (GeneralCalculatorClient calculator = new GeneralCalculatorClient(httpBinding, httpAddress_iisHost))
      {
        try
        {
          Console.WriteLine("Begin to invocate calculator service via http transport ");
          Console.WriteLine("x + y = {2} where x = {0} and y = {1}", 1, 2, calculator.Add(1, 2));
        }
        catch (Exception ex)
        {
          Console.WriteLine(ex.Message);
        }
      }
      #endregion
    }
    static void InvocateCalclatorServiceViaConfiguration()
    {
      Console.WriteLine("Invocate self-host calculator service ");
      Invocate Self-host service#region Invocate Self-host service
      using (GeneralCalculatorClient calculator_http = new GeneralCalculatorClient("selfHostEndpoint_http"))
      {
        using (GeneralCalculatorClient calculator_tcp = new GeneralCalculatorClient("selfHostEndpoint_tcp"))
        {
          try
          {
            Console.WriteLine("Begin to invocate calculator service via http transport ");
            Console.WriteLine("x + y = {2} where x = {0} and y = {1}", 1, 2, calculator_http.Add(1, 2));
            Console.WriteLine("Begin to invocate calculator service via tcp transport ");
            Console.WriteLine("x + y = {2} where x = {0} and y = {1}", 1, 2, calculator_tcp.Add(1, 2));
          }
          catch (Exception ex)
          {
            Console.WriteLine(ex.Message);
          }
        }
      }
      #endregion
      Console.WriteLine("\n\nInvocate IIS-host calculator service ");
      Invocate IIS-host service
#region Invocate IIS-host service
      using (GeneralCalculatorClient calculator = new GeneralCalculatorClient("iisHostEndpoint"))
      {
        try
        {
          Console.WriteLine("Begin to invocate calculator service via http transport ");
          Console.WriteLine("x + y = {2} where x = {0} and y = {1}", 1, 2, calculator.Add(1, 2));
        }
        catch (Exception ex)
        {
          Console.WriteLine(ex.Message);
        }
      }
      #endregion
    }
  }
}

6. Self-Hosting Configuration: Artech.WCFService.Hosting/App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="calculatorServieBehavior">
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="calculatorServieBehavior" name="Artech.WCFService.Service.GeneralCalculatorService">
         <endpoint address="" binding="basicHttpBinding" contract="Artech.WCFService.Contract.IGeneralCalculator">
        </endpoint>
        <endpoint address="" binding="netTcpBinding" contract="Artech.WCFService.Contract.IGeneralCalculator" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8888/generalcalculator" />
             <add baseAddress="net.tcp://localhost:9999/generalCalculator" />
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>
</configuration>

7. IIS-Host Configuration:

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="calculatorServiceBehavior">
     <serviceMetadata httpGetEnabled ="true"></serviceMetadata>
    </behavior>
   </serviceBehaviors>
  </behaviors>
  <services>
   <service name="Artech.WCFService.Service.GeneralCalculatorService" behaviorConfiguration="calculatorServiceBehavior">
    <endpoint binding="basicHttpBinding" contract="Artech.WCFService.Contract.IGeneralCalculator"></endpoint>
   </service>
  </services>
 </system.serviceModel>
  <system.web>
    <compilation debug="true">
      <assemblies>
        <add assembly="System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="Microsoft.Transactions.Bridge, Version=3.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="SMDiagnostics, Version=3.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.IdentityModel.Selectors, Version=3.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Web.RegularExpressions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Messaging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/></assemblies></compilation>
  </system.web>
</configuration>

8. Client configuration: Artech.WCFService.Client/App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <system.serviceModel>
  <client>
  <endpoint address="http://localhost:8888/generalCalculator" binding="basicHttpBinding" contract="Artech.WCFService.Contract.IGeneralCalculator" name="selfHostEndpoint_http"/>
    <endpoint address="net.tcp://localhost:9999/generalCalculator" binding="netTcpBinding" contract="Artech.WCFService.Contract.IGeneralCalculator" name="selfHostEndpoint_tcp"/>
    <endpoint address="http://localhost/wcfservice/GeneralCalculatorService.svc" binding="basicHttpBinding" contract="Artech.WCFService.Contract.IGeneralCalculator" name="iisHostEndpoint"/>
   </client>
 </system.serviceModel>
</configuration>

如何在Application中定義Endpoint

對於Self-Host的Service,絕大部分的Endpoint相關的信息都具有兩種定義方式——Managed Code 和Configuration。而對於把Service Host到IIS中的情況, Endpoint的信息一般虛擬根目錄下的Web.Config中定義。一般的我們我們不推薦使用代碼的方式Host和調用Service,這主要是基於以下的理由。首先我們開發的環境往往與部署的環境不盡相同,才用configuration的方式是的我們可以在部署的時候通過修改配置文件以適應新的需要。其次,對於不要出現的新的需要,比如對於一個原來只供Internet內部使用的Service,我們一般會定義一個基於TCP的Endpoint,現在出現來自於Internet的潛在用戶,我們只需要通過修改Config文件的方式為這個Service添加一個新的基於Http的Endpoint就可以了。 把Endpoint的信息寫在config文件中的優勢在於,修改config文件的內容是不需要重新編譯和重新部署的。相應的定義方式清參照以上的Sample。

下面我們來看看在host 一個Service的時候,置於配置文件的信息是如何起作用的。在上面的例子中我們通過下面一段代碼Host一個Serivice(對應得Service Type是GeneralCalculatorService)。

using (ServiceHost calculatorSerivceHost = new ServiceHost(typeof(GeneralCalculatorService)))
{
    calculatorSerivceHost.Opened += delegate
     {
       Console.WriteLine("Calculator Service has begun to listen ");
     };
     calculatorSerivceHost.Open();
     Console.Read();
}

下面是Service相關的配置信息:

<services>
      <service behaviorConfiguration="calculatorServieBehavior" name="Artech.WCFService.Service.GeneralCalculatorService">
         <endpoint address="" binding="basicHttpBinding" contract="Artech.WCFService.Contract.IGeneralCalculator">
        </endpoint>
        <endpoint address="" binding="netTcpBinding" contract="Artech.WCFService.Contract.IGeneralCalculator" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8888/generalcalculator" />
             <add baseAddress="net.tcp://localhost:9999/generalCalculator" />
          </baseAddresses>
        </host>
      </service>
</services>

首先我們創建一個ServiceHost對象calculatorSerivceHost,同時指定對用的Service Type 信息(typeof(GeneralCalculatorService))。WCF Infrastructure為在配置文件在Services Section尋找是否有相對用的service定義。在這個例子中,他會找到一個name屬性為Artech.WCFService.Service.GeneralCalculatorService的Service。然後他會根據定義在Service中的Endpoint定義為calculatorSerivceHost添加相應的Endpoint。 如果有對應的Endpoint Behavior設置存在於配置文件中,這些Behavior也會設置到改Endpoint中。最後調用Open方法,calculatorSerivceHost開始監聽來自Client端的請求。

Address

每一個Endpoint都必須有一個Address,Address定位和唯一標志一個Endpoint。在Managed code 中,Address由System.ServiceModel.EndpointAddress對象來表示。下面是一個Adress的結構:

URI:指定的Endpoint的Location。URI對於Endpoint是必須的。

Identity:當另一個Endpoint與此Endpoint進行消息交互時,可以獲取該Identity來Authenticate正在與之進行消息交互的Endpoint是否是它所希望的。Identity對於endpoint是可選的。

Headers:Address可以包含一些可選的Headers, 這些header最終會加到相應的Soap Message的Header中。Header存放的多為Address相關的信息,用於進行Addressing Filter。

Address的主要作用就是同過Uri為Service提供一個監聽Address。但在某些特殊的場景中,我們可以借助Address的Headers提供一些擴展的功能。在大多數的情況下Client可以直接訪問Service,換句話說,如果我們把Message 傳遞的路徑看成是以系列連續的節點(Node)的話,Message直接從Client所在的節點(Node)傳遞到最終的Service的節點。但在某些情況下,考慮的實現負載平衡,安全驗證等因素,我們需要在Client和最終的Service之間加入一些中間節點(Intermediaries),這些中間節點可以在Message到達最終Service Node之前作一些工作,比如為了實現負載平衡,它可以把Message Request分流到不同的節點——Routing;為了在Message達到最終Node之前,驗證Client是否是一個合法的請求,他可以根據Message存儲的Credential的信息驗證該請求——Authentication。

這些Intermediaries操作的一般不會是Message Body的內容(大多數情況下他們已經被加密),而是Message Header內容。他們可以修改Header的內容,也可以加入一些新的Header。所以為了實現Routing,我們需要在Message加入一些Addressing相關的內容,為了實現Authentication我們需要加入Client Credential的信息, 而這些信息都放在Header中。實際上你可以把很多內容加到Header中。

我們可以通過config文件加入這些Header:

<service behaviorConfiguration="calculatorServieBehavior" name="Artech.WCFService.Service.DuplexCalculatorService">
        <endpoint binding="wsDualHttpBinding" contract="Artech.WCFService.Contract.IDuplexCalculator">
          <headers>
            <role>admin</role>
          </headers>
        </endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:7777/DuplexCalculator" />
           </baseAddresses>
        </host>
      </service>
<client>
   <endpoint address="http://localhost/WCFService/SessionfulCalculatorService.svc"
     binding="wsHttpBinding" bindingConfiguration="" contract="Artech.WCFService.Contract.ISessionfulCalculator" >
<headers>
     <role>admin</role>
          </headers>
        </endpoint>
  </client>

Binding

WCF,顧名思義就是實現了分布式系統中各Application之間的Communication的問題。上面我們說過, Client和Service之間的通信完全有他們各自的Endpoint的擔當。Address解決了尋址的問題,通過Address,Client知道在哪裡可以找到它所希望的Service。但是知道了地址,只是實現的通信的第一步。

對於一個基於SOA的分布式系統來說,各Application之間的通信是通過Message Exchange來實現的。如何實現在各個Application之間 進行Message的交互,首先需要考慮的是采用怎樣的Transport,是采用Http呢,還是采用TCP或是其他,比如Named Pipe、MSMQ。其次需要考慮的是Message應該采取怎樣的編碼,是text/XML呢,還是Binary,或是MTOM;此外,對於一個企業級的分布式應用,Security與Robustness是我們必須考慮的問題——我們應該采用Transport Level的Security(SSL)還是Message Level的Security;如何確保我們的Message的傳遞是可靠的(Reliable Messaging); 如何把在各application中執行的操作納入同一個事物中(Transaction)。而這一些都是Binding需要解決的問題。所以我們可以說Binding實現了Client和Service通信的所有底層細節。

在WCF中,Binding一個Binding Element的集合,每個Binding Element解決Communication的某一個方面。所有的Binding Element大體上可以分為以下3類:

1.Transport Binding Element:實現Communication的Transport選取,每個Binding必須包含一格Transport Element。

2.Encoding Binding Element:解決傳遞數據的編碼的問題,每個Binding必須包含一個Encoding Element,一般由Transport Binding Element來提供。

3.Protocol Binding Element:解決Security,Reliable Messaging和Transaction的問題。

下邊這個表格列出了Binding中的各個層次結構。

Layer Options Required Transactions TransactionFlowBindingElement No Reliability ReliableSessionBindingElement No Security SecurityBindingElement No Encoding Text, Binary, MTOM, Custom Yes Transport TCP, Named Pipes, HTTP, HTTPS, MSMQ, Custom

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved