zoukankan      html  css  js  c++  java
  • WCF学习--我的第一个WCF例子

    Windows Communication Foundation(WCF)是由微软发展的一组数据通信的应用程序开发接口,可以翻译为Windows通讯接口。

    通信双方的沟通方式,由合约来订定。通信双方所遵循的通信方法,由协议绑定来订定。通信期间的安全性,由双方约定的安全性层次来订定。

    契约(Contract)

    WCF 的基本概念是以契约(Contract) 来定义双方沟通的协议,合约必须要以接口的方式来体现,而实际的服务代码必须要由这些合约接口派生并实现。合约分成了四种:
    数据契约(Data Contract),订定双方沟通时的数据格式。服务契约(Service Contract),订定服务的定义。操作约(Operation Contract),订定服务提供的方法。消息约(Message Contract),订定在通信期间改写消息内容的规范。

    协议绑定 (Binding)

    由于 WCF 支持了HTTPTCP,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)
     
      一般地,我们通过接口的形式定义服务契约,下面代码将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();
                  }
            }
        }
    

      

    现在服务已经启动,下面实现客户端的调用。(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();
                   }
               }
            }
        }
    

     

    2:添加服务引用

    利用svcUtil.exe生成代码,输入http://127.0.0.1:9999/HelloWord/HelloWord参数(添加svcutil.exe见http://www.cnblogs.com/scottckt/archive/2012/05/20/2510716.html

    生成一个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-PCAdministrator" />
                    </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);
            }
        }
    

      运行结果

                       

    以上为新手学习,高手大神就绕过啦,和大家一起学习

  • 相关阅读:
    继续对dubbo源代码进行maven builder
    Oracle操作XML各种场景介绍
    GitHub上的SliddingMenu滑动过程中卡顿问题的解决的方法
    [leetcode] Reverse Words in a String [1]
    UI标签库专题五:JEECG智能开发平台 Tabs(选项卡父标签)
    JAVA的一次编译,到处执行,你知道多少?
    设计模式学习--------12.代理模式学习
    P3573 [POI2014]RAJ-Rally
    2019-2-21-PowerShell-通过-WMI-获取补丁
    2019-2-21-PowerShell-通过-WMI-获取补丁
  • 原文地址:https://www.cnblogs.com/zb-success/p/3652962.html
Copyright © 2011-2022 走看看