天天看點

WCF學習--我的第一個WCF例子

Windows Communication Foundation(WCF)是由微軟發展的一組資料通信的應用程式開發接口,可以翻譯為Windows通訊接口。

通信雙方的溝通方式,由合約來訂定。通信雙方所遵循的通信方法,由協定綁定來訂定。通信期間的安全性,由雙方約定的安全性層次來訂定。

契約(Contract)

WCF 的基本概念是以 契約(Contract) 來定義雙方溝通的協定,合約必須要以接口的方式來展現,而實際的服務代碼必須要由這些合約接口派生并實作。合約分成了四種: 資料契約(Data Contract),訂定雙方溝通時的資料格式。服務契約(Service Contract),訂定服務的定義。 操作 契約(Operation Contract),訂定服務提供的方法。 消息 契約(Message Contract),訂定在通信期間改寫消息内容的規範。

協定綁定 (Binding)

由于 WCF 支援了HTTP,TCP,Named Pipe,MSMQ,Peer-To-Peer TCP 等協定,而 HTTP 又分為基本 HTTP 支援 (BasicHttpBinding) 以及 WS-HTTP 支援 (WsHttpBinding),而 TCP 亦支援 NetTcpBinding,NetPeerTcpBinding 等通信方式,是以,雙方必須要統一通信的協定,并且也要在編碼以及格式上要有所一緻。

安全性層次

WCF 實作上已經支援了傳輸層次安全性 (Transport-level security) 以及消息層次安全性 (Message-level security) 兩種。 傳輸層次安全性:在資料傳輸時期加密,例如 SSL。消息層次安全性:在 資料處理時就加密,例如使用 數字簽名,散列或是使用 密鑰加密法等。 (以上概念從百度百科複制而來,希望對大家有所幫助。)   建立控制台項目實作服務端(WCF_Conosle_Service)

WCF學習--我的第一個WCF例子

    一般地,我們通過接口的形式定義服務契約,下面代碼将IHelloWord定義成服務契約

[ServiceContract]
   public interface IHelloWorld
    {
        [OperationContract]
        string GetData();
    }
           

  通過應用ServiceContractAttribute特性将接口定義成服務契約,要在相應的操作方法上面顯式地應用OperationContractAttribute特性。

     HelloWorld實作IHelloWorld接口,并具體實作接口定義的方法。

public class HelloWorld :IHelloWorld
    {
       public string GetData()
        {
            return "Hello World";
        }
    }
           

  在Program中實作WCF服務的啟動

class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(HelloWorld)))
              {
                  host.AddServiceEndpoint(typeof(IHelloWorld), new WSHttpBinding(), "http://127.0.0.1:9999/HelloWord");
                  if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                  {
                      ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                      behavior.HttpGetEnabled = true;
                      behavior.HttpGetUrl = new Uri("http://127.0.0.1:9999/HelloWord/HelloWord");
                      host.Description.Behaviors.Add(behavior);
                  }
                  host.Opened += delegate
                  {
                      Console.WriteLine("CalculaorService已經啟動,按任意鍵終止服務!");
                  };
   
                  host.Open();
                  Console.Read();
              }
        }
    }
           

  

WCF學習--我的第一個WCF例子

現在服務已經啟動,下面實作用戶端的調用。(Client層)

有兩種實作方式:

1:用戶端層引用服務端DLL(WCF_Console_Service)

class Program
    {
        static void Main(string[] args)
        {
            using (ChannelFactory<IHelloWorld> channelFactory = new ChannelFactory<IHelloWorld>(new WSHttpBinding(), "http://127.0.0.1:9999/HelloWord"))
           {
               IHelloWorld proxy = channelFactory.CreateChannel();
               using (proxy as IDisposable)
               {
                   string t = proxy.GetData();
               }
           }
        }
    }
           

 

WCF學習--我的第一個WCF例子

2:添加服務引用

WCF學習--我的第一個WCF例子

利用svcUtil.exe生成代碼,輸入http://127.0.0.1:9999/HelloWord/HelloWord參數(添加svcutil.exe見http://www.cnblogs.com/scottckt/archive/2012/05/20/2510716.html)

WCF學習--我的第一個WCF例子

生成一個cs檔案和一個config檔案,生成的cs檔案為

//------------------------------------------------------------------------------
// <auto-generated>
//     此代碼由工具生成。
//     運作時版本:2.0.50727.5472
//
//     對此檔案的更改可能會導緻不正确的行為,并且如果
//     重新生成代碼,這些更改将會丢失。
// </auto-generated>
//------------------------------------------------------------------------------



[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="IHelloWorld")]
public interface IHelloWorld
{
    
    [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IHelloWorld/GetData", ReplyAction="http://tempuri.org/IHelloWorld/GetDataResponse")]
    string GetData();
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface IHelloWorldChannel : IHelloWorld, System.ServiceModel.IClientChannel
{
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class HelloWorldClient : System.ServiceModel.ClientBase<IHelloWorld>, IHelloWorld
{
    
    public HelloWorldClient()
    {
    }
    
    public HelloWorldClient(string endpointConfigurationName) : 
            base(endpointConfigurationName)
    {
    }
    
    public HelloWorldClient(string endpointConfigurationName, string remoteAddress) : 
            base(endpointConfigurationName, remoteAddress)
    {
    }
    
    public HelloWorldClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(endpointConfigurationName, remoteAddress)
    {
    }
    
    public HelloWorldClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(binding, remoteAddress)
    {
    }
    
    public string GetData()
    {
        return base.Channel.GetData();
    }
}
           

  生成的config為

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_IHelloWorld" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                    allowCookies="false">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Message">
                        <transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="Windows" negotiateServiceCredential="true"
                            algorithmSuite="Default" establishSecurityContext="true" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://127.0.0.1:9999/HelloWord" binding="wsHttpBinding"
                bindingConfiguration="WSHttpBinding_IHelloWorld" contract="IHelloWorld"
                name="WSHttpBinding_IHelloWorld">
                <identity>
                    <userPrincipalName value="zb-PC\Administrator" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>
           

  Program代碼為

class Program
    {
        static void Main(string[] args)
        {
            HelloWorldClient client = new HelloWorldClient();
            string s = client.GetData();
            Console.WriteLine(s);
        }
    }
           

  運作結果

WCF學習--我的第一個WCF例子

以上為新手學習,高手大神就繞過啦,和大家一起學習

轉載于:https://www.cnblogs.com/zb-success/p/3652962.html

繼續閱讀